NSMutableURLRequest使用POST返回null

时间:2012-12-24 13:55:26

标签: iphone ios nsmutableurlrequest

根据标题,当我添加POST请求时,我相信NSMutableURLRequest正在返回null?我的服务器端已全部设置完毕,我可以curl -F "test=test" 127.0.0.1获得我想要的结果。

从下面的方法中可以看出,我已经放置了一些NSLog用于错误测试。 didReceiveResponseconnectionDidFinishLoading方法有效didReceiveData无法调用。类似于当我使用curl时没有放置POST消息并且什么也没有结果。由此导致我认为我错过了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;
}

1 个答案:

答案 0 :(得分:2)

请求Content-Type应设置为application/x-www-form-urlencoded