在NSURLRequest中通过POST发送JSON

时间:2011-09-13 15:34:16

标签: iphone objective-c post nsurlconnection

我在使用REST API向服务器发送JSON时遇到问题。 这是我使用的代码:

NSString *jsonPostBody = [NSString stringWithFormat:@"'json' = '{\"user\":{\"username\":"
                          "\"%@\""
                          ",\"password\":"
                          "\"%@\""
                          "}}'",
                          [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                          [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];       
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *apiPathParams = [NSString stringWithFormat:@"%@",
                           @"getUser"
                           ];

NSURL *url = [NSURL URLWithString:[[apiPath retain] stringByAppendingString:apiPathParams]];    
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval:180.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSString* postDataLengthString = [[NSString alloc] initWithFormat:@"%d", [postData length]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:postDataLengthString forHTTPHeaderField:@"Content-Length"];
[self internalRequest:request];

这就是API的样子,如果它是一个html格式:

<form method="post" action="someAPI-URL">
<input name="json" value="{"user":...}" />
</form>

这是我将POST数据添加到请求时的样子:

json={"user":{"username":"someUser","password":"somePassword"}}

由于某种原因,我不知道POST数据没有到达服务器。 我在dataString的格式化方面做错了吗? 我如何格式化我的dataString以便它匹配String如上所示的表格将传递给服务器?

任何帮助都将受到高度赞赏。

P.S。我宁愿不使用ASIHttpRequest,因为我接管了其他人的项目,除了这个post-request之外,其他所有请求都能正常工作。 因此,将整个批量更改为其他连接框架将非常耗时。

这是internalRequest Method的源代码

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
NSMutableDictionary *di = [NSMutableDictionary dictionaryWithObject:[[NSMutableData alloc] init] forKey:@"receivedData"];   
[di setObject:[NSString stringWithFormat:@"%i",identifier] forKey:@"identifier"];
if (delegate == nil) 
{ 
    delegate = self;         
}
[di setObject:delegate forKey:@"delegate"];

CFDictionaryAddValue(connectionToInfoMapping, connection, di)

4 个答案:

答案 0 :(得分:18)

因为您尝试提交类似

的HTTP POST标头

json={"user":{"username":"%@","password":"%@"}}

这个例子完全有资格让人感到困惑。

它是整个身体的application/x-www-form-urlencoded和价值application/json的混合物。

也许是解决此问题的方法:

您可能需要调整该HTTP标头:

 [request setValue:@"application/x-www-form-urlencoded" 
forHTTPHeaderField:@"Content-Type"];

由于HTTP主体的JSON部分(值)的编码:

[request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                      dataUsingEncoding:NSUTF8StringEncoding 
                   allowLossyConversion:YES]];    

其中stringByAddingPercentEscapesUsingEncoding是PHP等效urlencode的客观c jabberwocky。

HTH

答案 1 :(得分:0)

我认为你必须使用JSON框架并在发送之前将jsonPostBody转换为它的JSON表示。查看this accepted answer,它会显示如何构建请求。

答案 2 :(得分:0)

此Web服务是否具有可以使用浏览器并进行测试的Web客户端。我建议你,如果他们有一个Web客户端已经尝试使用Mozilla Firefox与插件firebug并检查哪些数据和标头正在发送给服务器请求也可以在post data选项卡中看到json字符串。

确定服务器期望的消息后,您可以自己创建完全相同的消息并发送。

为什么你试图创建自己的json我不知道,但我建议你使用第三方库,如JSON Framework。另外,我建议您使用ASIHttpRequest库来获取http请求。它让一切都变得轻松。

但首先要做的是,你需要确定消息的类型,参数,标题,类型和数据是什么......

答案 3 :(得分:0)

您可以使用the Chrome Advanced Rest Client测试不同的标头和表单参数。因此,在编码之前,您可以使用此工具了解Web服务的行为。