在 NSURLRequest 中通过 POST 发送 JSON [英] Sending a JSON via POST in NSURLRequest

查看:34
本文介绍了在 NSURLRequest 中通过 POST 发送 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem with sending a JSON to a Server with REST API. This is the code i use:

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];

如果它是 html 表单,API 会是什么样子:

This is what the API would look like, if it was a html form:

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

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

This is what my POST Data looks like when i add it to the request:

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

出于某种原因,我不知道 POST 数据没有到达服务器.我对 dataString 的格式做错了吗?我必须如何准确地格式化我的 dataString 以便它匹配上面显示的表单将传递到服务器的字符串?

For a reason I don't know the POST Data does not arrive at the server. Have i done something wrong with the formatting of the dataString? How exactly must i format my dataString so that it matches the String a form as shown above would deliver to the server?

任何帮助将不胜感激.

附言我宁愿不使用 ASIHttpRequest,因为我从其他人那里接手了这个项目,除了这个 post-request 之外,所有其他请求都可以正常工作.因此,将整个批量更改为其他连接框架将非常耗时.

P.S. I would rather not use ASIHttpRequest, since i took over the project from somebody else an every other request works fine, except this post-request. So changing this whole bulk to an other connection framework would be very time consuming.

这里是internalRequest方法的源码

Here is the internalRequest Method's sourcecode

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)

推荐答案

因为你尝试提交一个像

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

这个例子完全有资格导致混乱.

this example is fully qualified to end up in confusion.

它混合了 application/x-www-form-urlencoded 用于整个 body 和 application/json 用于值.

It's a mixture of application/x-www-form-urlencoded for the whole body and application/json for the value.

也许可以解决这个问题:

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

You'll probably need to adjust that HTTP header:

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

由于 HTTP 正文的 JSON 部分(值)的编码:

due to an encoding of the JSON part (value) of the HTTP body:

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

其中 stringByAddingPercentEscapesUsingEncoding 是 PHP 等效 urlencode 的目标 c jabberwocky.

where stringByAddingPercentEscapesUsingEncoding is objective c jabberwocky for the PHP equivalent urlencode.

HTH

这篇关于在 NSURLRequest 中通过 POST 发送 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆