2

根据标题,我相信当我添加 POST 请求时NSMutableURLRequest会返回?null我的服务器端已全部设置好,我能够curl -F "test=test" 127.0.0.1得到我想要的结果。

从下面的方法中可以看出,我已经放置了几个NSLogs 用于错误测试。和方法有效但didReceiveResponse未能调用。类似于我在使用 curl 时没有放置 POST 消息并且没有任何结果。由此,我认为我在方法中遗漏了一些东西。connectionDidFinishLoadingdidReceiveDataviewDidLoad

我还在最底部添加了如何使用 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;
}
4

1 回答 1

2

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

于 2012-12-24T19:53:33.017 回答