Mav*_*1st 10 iphone post objective-c 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];
Run Code Online (Sandbox Code Playgroud)
这就是API的样子,如果它是一个html表单:
<form method="post" action="someAPI-URL">
<input name="json" value="{"user":...}" />
</form>
Run Code Online (Sandbox Code Playgroud)
这是我将POST数据添加到请求时的样子:
json={"user":{"username":"someUser","password":"somePassword"}}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,我不知道POST数据没有到达服务器.我在dataString的格式化方面做错了吗?我如何格式化我的dataString以便它匹配String如上所示的表格将传递给服务器?
任何帮助将受到高度赞赏.
PS我宁愿不使用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)
Run Code Online (Sandbox Code Playgroud)
kla*_*aus 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"];
Run Code Online (Sandbox Code Playgroud)
由于HTTP主体的JSON部分(值)的编码:
[request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
dataUsingEncoding:NSUTF8StringEncoding
allowLossyConversion:YES]];
Run Code Online (Sandbox Code Playgroud)
哪里stringByAddingPercentEscapesUsingEncoding
是PHP等效的客观c jabberwocky urlencode
.
HTH
归档时间: |
|
查看次数: |
29307 次 |
最近记录: |