Sending a JSON via POST in NSURLRequest

前端 未结 4 2008
轻奢々
轻奢々 2020-12-08 17:07

I have a problem with sending a JSON to a Server with REST API. This is the code i use:

NSString *jsonPostBody = [NSString stringWithFormat:@\"\'json\' = \'{         


        
相关标签:
4条回答
  • 2020-12-08 17:54

    I think you have to use a JSON framework and convert jsonPostBody to it's JSON representation before sending it. Check this accepted answer , it shows how to build the request.

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

    since you try to submit a HTTP POST header like

    json={"user":{"username":"%@","password":"%@"}},

    this example is fully qualified to end up in confusion.

    It's a mixture of application/x-www-form-urlencoded for the whole body and application/json for the value.

    Maybe a way to resolve this:

    You'll probably need to adjust that HTTP header:

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

    due to an encoding of the JSON part (value) of the HTTP body:

    [request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                          dataUsingEncoding:NSUTF8StringEncoding 
                       allowLossyConversion:YES]];    
    

    where stringByAddingPercentEscapesUsingEncoding is objective c jabberwocky for the PHP equivalent urlencode.

    HTH

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

    Does this web service has a web client that you can use your browser and test. I reccomend you that if they have a web client already try using Mozilla Firefox with the plug-in firebug and check what data and headers are being sent to server with a request also it is possible to see the json string in post data tab.

    After you make sure what sort of message the server expect then you can create the exact same message by yourself and send it.

    For what reason you try to create your own json I dont know, but I reccomend you to use a third party library such as JSON Framework. Also I reccomend you to use ASIHttpRequest library for http requests. It makes everything eaasy.

    But first thing is first, you need to be sure the type of the message, what are the parameters, headers, type and data...

    0 讨论(0)
  • 2020-12-08 18:06

    You can test different headers and form parameters using the Chrome Advanced Rest Client. So, before coding you could know how the web service is behaving using this tool.

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