iOS 中的 HttpRequest Body 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15898979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:07:39  来源:igfitidea点击:

HttpRequest Body parameters in iOS

iosxcodexmlhttprequest

提问by xrnd

I am using web service for my iOS app. I know how to send http post request via URL (not http Body) and get response using NSURLConnection Delegate. But now there is better approach which I am following for web service and passing parameters in request body. I looked for library on google and found this.

我正在为我的 iOS 应用程序使用网络服务。我知道如何通过 URL(不是 http Body)发送 http post 请求并使用 NSURLConnection Delegate 获取响应。但是现在有更好的方法可以用于 Web 服务并在请求正文中传递参数。我在谷歌上寻找图书馆并找到了这个

But the code is bit difficult for me and I suppose there should be function for the same, which can make this bit easier. Is there any? the code so far is below.

但是代码对我来说有点困难,我想应该有相同的功能,这可以使这更容易一些。有没有?到目前为止的代码如下。

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
    initWithURL:[NSURL 
    URLWithString:**WebService URL**]];

[request setHTTPMethod:@"POST"];
[request setValue:@"text/json" forHTTPHeaderField:@"Content-type"];

NSString *jsonString = [NSString stringWithFormat:@"{\n\"username\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":%@,\n\"%@\":%@,\n\"version\":%@,\n\"name\":\"%@\"\n}",userName, @"password",pass,@"accessToken",token,@"isOnline",@"True",@"accountType",type,@"False",name];

[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

jsonString in this code is the http body. I want to pass parameters in request body. Now, after executing this code i get null in NSData variable. whereas my web service function returns a value and also it returns if the execution was successful. what is wrong in my code. Thank you.

这段代码中的 jsonString 是 http 主体。我想在请求正文中传递参数。现在,在执行这段代码后,我在 NSData 变量中得到了空值。而我的 web 服务函数返回一个值,如果执行成功,它也会返回。我的代码有什么问题。谢谢你。

回答by xrnd

Thanks for your answers. Finally I found the exact solution which works absolutely fine. I have used NSURLConnection delegate and I am passing parameter in HTTPBody in json. I am receiving response also in json. But sending parameter directly as json is not permitted in httprequestbody so we need to take it in NSData and set content-type.

感谢您的回答。最后,我找到了绝对有效的确切解决方案。我使用了 NSURLConnection 委托,并且在 json 中的 HTTPBody 中传递参数。我也在 json 中收到回复。但是在 httprequestbody 中不允许直接以 json 形式发送参数,因此我们需要将其放入 NSData 并设置 content-type。

Note: specifying content type is very important.

注意:指定内容类型非常重要。

 -(void)sendDataToServer:(NSString*)userName :(NSString*)name{
 {
 NSArray *keys = [NSArray arrayWithObjects: @"name",@"accountType",@"isOnline",@"username", nil];
NSArray *objects = [NSArray arrayWithObjects:name,[NSNumber numberWithBool:false],[NSNumber numberWithBool:false],userName, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSString *myJSONString =[jsonDictionary JSONRepresentation];
NSData *myJSONData =[myJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"myJSONString :%@", myJSONString);
NSLog(@"myJSONData :%@", myJSONData);

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:Your URL string]];
[request setHTTPBody:myJSONData];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];


  if (theConnection) {
      NSLog(@"connected");
      receivedData=[[NSMutableData alloc]init];
  } else {

      NSLog(@"not connected");
  }

  }

  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
   [receivedData setLength:0];
}

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response: %@",responseString);
}

 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(@"Succeeded! Received %lu data",(unsigned long)[receivedData length]);
NSString* responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"response: %@",responseString);


 NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];

// show all values

for(id key in res) {

    id value = [res objectForKey:key];

    NSString *keyAsString = (NSString *)key;
    NSString *valueAsString = (NSString *)value;

    NSLog(@"key: %@", keyAsString);
    NSLog(@"value: %@", valueAsString);
}  
}

P.S : You will need to add JSon files for serialization(json.h).

PS:您需要添加用于序列化的 JSon 文件(json.h)。

回答by vdaubry

There is a typo in your sample code, this would explain the null result :

您的示例代码中有一个错字,这可以解释空结果:

NSString ***jsonString** = [NSString stringWithFormat:@"{\n\"username\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":%@,\n\"%@\":%@,\n\"version\":%@,\n\"name\":\"%@\"\n}",userName, @"password",pass,@"accessToken",token,@"isOnline",@"True",@"accountType",type,@"False",name];

[request setHTTPBody:[**xmlString** dataUsingEncoding:NSUTF8StringEncoding]];

回答by fengd

Check out this question nsurlrequest post bodyand this http post encode type

查看这个问题nsurlrequest post body和这个http post encode type

Generally, the body should conforms to "key=value" format

通常,正文应符合“key=value”格式

To your question, you need a "key" for your jsonString

对于您的问题,您需要一个“钥匙” jsonString

[request setHTTPBody:[NSString stringWithFormat:@"postedJson=%@", jsonString]];

postedJsonis the key through which you'll get the value of it at server side. such as:

postedJson是您在服务器端获得它的价值的关键。如:

request["postedJson"]

the value returned would be the jsonStringyou construted

返回的值将是jsonString你构造的