NSURLRequest cannot handle HTTP body when method is not POST?

前端 未结 3 1587
醉话见心
醉话见心 2020-12-17 17:01

Whenever I set a body on a mutable request with the method set to anything other than POST, the body is not included in the request and I get a kCFErrorDomainCFNetwork error

相关标签:
3条回答
  • 2020-12-17 17:40

    Are you remembering to set the Content-Length/Transfer-Encoding and Content-Type headers? I don't think that Content-Length is put in automatically for you, which means the server is going to assume it's 0.

    More info: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

    0 讨论(0)
  • 2020-12-17 17:59

    I tried finding more recent information about it, but there was an old post about the exact issue you were talking about: http://lists.apple.com/archives/cocoa-dev/2004/May/msg01847.html

    Basically, they mention it is a bug in the code. Sadly, I wished I could find something more recent that confirms it.

    The code I've been using is ASIHTTPRequest and it can definitely do PUT requests, since they use a lower level set of code to create the HTTP messages and don't rely on the NSMutableUrlRequest.

    Also, I found another blog post talking about the issue and what you need to put for a PUT request. http://iphonedevelopment.blogspot.com/2008/06/http-put-and-nsmutableurlrequest.html

    blog post:

    When using NSMutableURLRequest to do an HTTP PUT request, add the following line of code (req is the NSMutableURLRequest):

    [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    

    That's all there is to it. If you add this line of code, your PUT requests will work just fine.

    0 讨论(0)
  • 2020-12-17 18:04

    here it is

    +(NSString*)simpleCurl:(NSString*)urlStr withBody:(NSString*)post{
    
    //    NSLog(urlStr);
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    //    NSLog([url description]);
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req setHTTPMethod:@"POST"];
    [req setValue:@"close" forHTTPHeaderField:@"Connection"];
    [req setValue:@"utf-8;q=0.7,*;q=0.7" forHTTPHeaderField:@"Accept-Charset"];
    [req setValue:@"gzip,deflate" forHTTPHeaderField:@"Accept-Encoding"];
    [req setValue:@"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)" forHTTPHeaderField:@"User-Agent"];
    [req setValue:@"Application/Json, text/html, application/xhtml+xml, */*" forHTTPHeaderField:@"Accept"];
    [req setHTTPMethod:@"POST"];//  or PUT
    NSString *postString = post;
    [req setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSData *res = [NSURLConnection  sendSynchronousRequest:req returningResponse:NULL error:NULL];
    NSString* html=[[NSString alloc] initWithData:res encoding:NSUTF8StringEncoding];
    return html;
    

    }

    0 讨论(0)
提交回复
热议问题