0

I have an API on the server that I am trying to get a JSON response from. I have used several request tools to simulate a call, and get the correct data back each time. Here is my request setup:

NSString *post = [NSString stringWithFormat:@"user_id=%@&last_sync=%@",user_id, last_sync];
NSURL *directoryURL = [NSURL URLWithString:directoryURI];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:directoryURL];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[NSData dataWithBytes:[post UTF8String] length:[post length]]];

The content type is also the same on my simulated requests. There are no errors returned, just no content.

4

4 回答 4

1

I use the AFNetworking library, which takes a lot of the pain out of HTTP comms.

My POST calls are along the lines below:

NSURL *nsURL = [NSURL URLWithString:@"http://someurl.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsURL];

[request setHTTPMethod:@"POST"];
[request addValue:@"xxxx" forHTTPHeaderField:@"yyy"]; // for any header params you want to pass in
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

// If you need to pass any JSOn data to your WS
if (json != nil) [request setHTTPBody:json];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *returnedRequest, NSHTTPURLResponse *response, id JSON)
{
    ...
}
failure:^(NSURLRequest *returnedRequest, NSHTTPURLResponse *response, NSError *error, id JSON)
{
       ...
}];
于 2013-07-31T23:07:08.227 回答
1

Figured it out. Apparently, unlike the simulators, NSMutableRequest does NOT like when you use a combination of POST variables, and a querystring variable in the URL. Moved the variable into the POST body and everything works fine now.

于 2013-08-01T11:45:26.530 回答
0

If you are using POST method, you have to convert your string into NSData format.

Hope this will help.

于 2013-07-31T20:24:38.003 回答
0

URL Form Parameter Encoding [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/ Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3 JSON Parameter Encoding

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/ Content-Type: application/json {"foo": "bar", "baz": [1,2,3]}

于 2014-06-18T03:43:12.373 回答