[英]iOS: How do I handle the following parameter request?
我想知道如何處理以下參數PUT
請求? 我如何存儲參數(假設使用NSDictionary
),以便可以將其發送到運行php的服務器。 任何提示或建議,不勝感激。
curl -X PUT -d {"questions":[{"type":"control_head" }]}
ps以上是API文檔給我的。 {"questions":[{"type":"control_head" }]}
是我需要使用的參數,以防萬一。
如果您自己執行此操作,則將實例化一個NSMutableURLRequest
對象,根據您的curl
建議修改它(例如PUT
請求,JSON主體等),然后通過NSURLConnection
或NSURLSession
發起請求。
產生類似:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"PUT";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *parameters = @{@"questions":@[@{@"type": @"control_head"}]};
NSError *error;
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data) {
NSLog(@"sendAsynchronousRequest error: %@", connectionError);
return;
}
// parse the response here; given that the request was JSON, I assume the response is, too:
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!responseObject) {
NSLog(@"parsing response failed: %@", parseError);
NSLog(@"body of response was: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return;
}
// now you can look at `responseObject`
}];
您可以使用AFNetworking之類的庫進一步簡化此操作 :
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = @{@"questions":@[@{@"type": @"control_head"}]};
[manager PUT:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
(我還沒有檢查AFNetworking請求的語法,但這有點類似。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.