【发布时间】:2015-09-18 12:20:42
【问题描述】:
我需要在对象中绑定参数并将对象作为 POST 请求传递,以从 API 接收成功的信息。
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc@xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
这是我需要与发布请求一起发送的对象。但是当我将它转换为字符串并发布时,整个对象成为键,值成为nil。它被发布为{"{customer.....}=>nil}。
该对象应发布为
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc@xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
这是我目前的尝试:
NSArray *objects = [[NSArray alloc] initWithObjects:@"",@"3e708bf1a49cdd06",@"abc@xyz.in",@"abc",@"1234567890",@"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:@"auth_token",@"device_id",@"email_address",@"name",@"number",@"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,@"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:@"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
这里使用的很多代码都是在没有正确理解的情况下使用的,并且直接取自其他 StackOverflow 答案,因此请原谅任何不良的编程习惯。
我该怎么做?任何帮助表示赞赏。谢谢。
【问题讨论】:
-
API 对编码的要求是什么?看起来他们需要 JSON 内容,所以我首先尝试确保将其设置为请求 body 而不是参数,并为
Content-Type指定text/json或text/html跨度> -
我刚刚检查过了。 API 要求数据是原始的,而不是 JSON。如何通过向 API 发送原始字符串来发出 POST 请求?