![](/img/trans.png)
[英]POST HTTP Request from iOS to RESTful WCF Service .NET 4.0
[英]iOS http POST request
我在服務器上有一個API,我試圖從中獲取JSON響應。 我使用了幾個請求工具來模擬調用,並且每次都返回正確的數據。 這是我的請求設置:
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]]];
內容類型在我的模擬請求中也是相同的。 沒有返回錯誤,只是沒有內容。
我使用AFNetworking庫,它消除了HTTP通信帶來的很多痛苦。
我的POST電話如下:
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)
{
...
}];
弄清楚了。 顯然,與模擬器不同,當您使用POST變量和URL中的查詢字符串變量時,NSMutableRequest不喜歡。 將變量移動到POST主體中,一切正常。
如果您使用的是POST方法,則必須將字符串轉換為NSData格式。
希望這會有所幫助。
URL表單參數編碼[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/ Content-Type: application/x-www-form-urlencoded
[[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
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/ Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.