在 NSURLRequest 中通过 POST 发送 JSON
我在使用 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];
如果它是 html 表单,这就是 API 的样子:
<form method="post" action="someAPI-URL">
<input name="json" value="{"user":...}" />
</form>
当我将其添加到请求中时,这就是我的 POST 数据的样子:
json={"user":{"username":"someUser","password":"somePassword"}}
由于某种原因,我不知道 POST 数据未到达服务器。 我对 dataString 的格式做错了什么吗? 我到底必须如何格式化我的 dataString 以便它与上面所示的表单将传递到服务器的字符串相匹配?
任何帮助将不胜感激。
PS 我宁愿不使用 ASIHttpRequest,因为我从其他人那里接管了该项目,除了这个后期请求之外,所有其他请求都工作正常。 因此,将整个批量更改为其他连接框架将非常耗时。
这是internalRequest方法的源代码
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)
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];
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>
This is what my POST Data looks like when i add it to the request:
json={"user":{"username":"someUser","password":"somePassword"}}
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?
Any help would be highly appreciated.
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.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您尝试提交像
json={"user":{"username":"%@","password":"%@"}}
这样的 HTTP POST 标头,因此此示例是完全限定的最终陷入混乱。
它是整个主体的
application/x-www-form-urlencoded
和值的application/json
的混合。也许有一种方法可以解决此问题:
您可能需要调整该 HTTP 标头:
由于 HTTP 正文的 JSON 部分(值)的编码:
其中
stringByAddingPercentEscapesUsingEncoding
是 Objective C jabberwocky,相当于 PHP 的urlencode
。华泰
since you try to submit a HTTP POST header like
json={"user":{"username":"%@","password":"%@"}}
,this example is fully qualified to end up in confusion.
It's a mixture of
application/x-www-form-urlencoded
for the whole body andapplication/json
for the value.Maybe a way to resolve this:
You'll probably need to adjust that HTTP header:
due to an encoding of the JSON part (value) of the HTTP body:
where
stringByAddingPercentEscapesUsingEncoding
is objective c jabberwocky for the PHP equivalenturlencode
.HTH
我认为您必须使用 JSON 框架并在发送之前将 jsonPostBody 转换为其 JSON 表示形式。检查这个接受的答案 ,它显示了如何构建请求。
I think you have to use a JSON framework and convert
jsonPostBody
to it's JSON representation before sending it. Check this accepted answer , it shows how to build the request.此 Web 服务是否有一个 Web 客户端,您可以使用浏览器进行测试。我建议您,如果他们已经有一个 Web 客户端,请尝试使用带有 Firebug 插件的 Mozilla Firefox,并检查通过请求将哪些数据和标头发送到服务器,还可以在发布数据选项卡中看到 json 字符串。
在确定服务器期望什么类型的消息后,您可以自己创建完全相同的消息并发送它。
我不知道你出于什么原因尝试创建自己的 json,但我建议你使用第三方库,例如 JSON Framework。我还建议您使用 ASIHttpRequest 库来处理 http 请求。它让一切变得简单。
但首先,您需要确定消息的类型,参数、标头、类型和数据是什么……
Does this web service has a web client that you can use your browser and test. I reccomend you that if they have a web client already try using Mozilla Firefox with the plug-in firebug and check what data and headers are being sent to server with a request also it is possible to see the json string in post data tab.
After you make sure what sort of message the server expect then you can create the exact same message by yourself and send it.
For what reason you try to create your own json I dont know, but I reccomend you to use a third party library such as JSON Framework. Also I reccomend you to use ASIHttpRequest library for http requests. It makes everything eaasy.
But first thing is first, you need to be sure the type of the message, what are the parameters, headers, type and data...
您可以使用Chrome 高级 Rest 客户端。因此,在编码之前,您可以使用此工具了解 Web 服务的行为方式。
You can test different headers and form parameters using the Chrome Advanced Rest Client. So, before coding you could know how the web service is behaving using this tool.