根据标题,我相信当我添加 POST 请求时NSMutableURLRequest
会返回?null
我的服务器端已全部设置好,我能够curl -F "test=test" 127.0.0.1
得到我想要的结果。
从下面的方法中可以看出,我已经放置了几个NSLog
s 用于错误测试。和方法有效但didReceiveResponse
未能调用。类似于我在使用 curl 时没有放置 POST 消息并且没有任何结果。由此,我认为我在方法中遗漏了一些东西。connectionDidFinishLoading
didReceiveData
viewDidLoad
我还在最底部添加了如何使用 json 编码从服务器发送响应。
所以我错过了什么吗?
- (void)viewDidLoad {
NSString *yourPostString = [NSString stringWithFormat:@"test=test"];
dataWebService = [NSMutableData data];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://127.0.0.1/"]];
NSString *postLength = [NSString stringWithFormat:@"%d", [yourPostString length]];
[request addValue:@"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[yourPostString dataUsingEncoding:NSUTF8StringEncoding]];
myConnection = [NSURLConnection connectionWithRequest:request delegate:self];
[myConnection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[dataWebService setLength:0];
NSLog(@"Received Response");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[dataWebService appendData:data];
NSLog(@"working %@", data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@",responseString);
}
这是发送响应功能。
function sendResponse($status = 200, $body = '', $content_type = 'text/html'){
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}