我试图发布到iOS中的网络服务器,但我收到了404错误。我工作人员能够从不同的系统发布在一个字符串的地址和数据:试图发送POST请求到iOS中的URL
我试图做同样的在Xcode下面的代码:
NSString *body = [NSString stringWithFormat:@"message?salu=mr&firstname=john&lastname=smith&[email protected]&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5"];
NSData *data = [body dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [data length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xx.xxx.xxx.xxx/api"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:data];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *reply = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", reply);
,并从上面的NSLog '回复' 的最后几行是:
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/api<br><br>
</body>
但是,我能够用下面的代码,在那里我收到预期的数据放在同一个地址执行“GET”:
NSMutableURLRequest *request2 = [[NSMutableURLRequest alloc] init];
[request2 setURL:[NSURL URLWithString:@"http://xx.xxx.xxx.xxx/api/message"]];
[request2 setHTTPMethod:@"GET"];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);
所以Web服务器在运行,它出现问题就出在我发布的方式。有谁知道我做错了什么?
无关,但一般应该避免'sendSynchronousRequest'。使用异步请求。此外,虽然你已经为测试目的硬编码身体,但当你开始更加动态地构建身体时,不要忘记做必要的百分比转义(例如[本答案的第1点] (http://stackoverflow.com/a/26153527/1271826))。或者使用像[AFNetworking](https://github.com/AFNetworking/AFNetworking)这样的框架来为你处理这些细节。 – Rob 2014-10-06 14:43:23
感谢您的帮助,我会记住这样做。 – jdeckman 2014-10-06 15:07:02