2013-07-31 79 views
0

我在服務器上有一個API,我試圖從中獲取JSON響應。我已經使用了幾個請求工具來模擬一個調用,並且每次都得到正確的數據。以下是我的請求設置:iOS http POST請求

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]]]; 

我的模擬請求中的內容類型也相同。沒有錯誤返回,只是沒有內容。

+0

'@ 「USER_ID =%@&last_sync =%@」'這不是POST這是查詢字符串 – meda

+0

我轉換字符串轉換爲數據並將其傳遞給HTTPBody,如下所述:http://developer.apple.com/library/ios/#documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/WorkingWithHTTPAndHTTPSRequests/WorkingWithHTTPAndHTTPS Requests.html –

+0

如果你有一個JSON API,那麼你的頭應該看起來像這樣:[request setValue:@「application/json」forHTTPHeaderField:@「Accept」]; [request setValue:@「application/json」forHTTPHeaderField:@「Content-Type」];' – meda

回答

1

想通了。顯然,與模擬器不同,NSMutableRequest不像當你使用POST變量和URL中的查詢字符串變量的組合。將變量移動到POST正文中,現在一切正常。

0

如果您使用POST方法,則必須將字符串轉換爲NSData格式。

希望這會有所幫助。

+0

這是示例代碼。我想出瞭解決辦法,但必須等到我可以將其作爲答案。謝謝。 –

1

我使用的AFNetworking庫,它從HTTP通信中消除了很多痛苦。

我的帖子電話是沿着以下線路:

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) 
{ 
     ... 
}]; 
0

URL形式參數編碼 [[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]}