【问题标题】:How to send an object as a parameter for a POST request in iOS?如何在 iOS 中发送对象作为 POST 请求的参数?
【发布时间】:2015-09-18 12:20:42
【问题描述】:

我需要在对象中绑定参数并将对象作为 POST 请求传递,以从 API 接收成功的信息。

{
  customer = {
    "auth_token" = "";
    "device_id" = 3e708bf1a49cdd06;
    "email_address" = "abc@xyz.in";
    name = abc;
    number = 1234567890;
    "resend_token" = true;
   };
}

这是我需要与发布请求一起发送的对象。但是当我将它转换为字符串并发布时,整个对象成为键,值成为nil。它被发布为{"{customer.....}=>nil}

该对象应发布为

    {"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc@xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}

这是我目前的尝试:

    NSArray *objects = [[NSArray alloc] initWithObjects:@"",@"3e708bf1a49cdd06",@"abc@xyz.in",@"abc",@"1234567890",@"true", nil];

    NSArray *keys = [[NSArray alloc] initWithObjects:@"auth_token",@"device_id",@"email_address",@"name",@"number",@"resend_token", nil];

    NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];

    NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,@"customer", nil];

    NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
    NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];

    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];

    [request setHTTPMethod:@"POST"];
    NSError *error = nil; NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

这里使用的很多代码都是在没有正确理解的情况下使用的,并且直接取自其他 StackOverflow 答案,因此请原谅任何不良的编程习惯。

我该怎么做?任何帮助表示赞赏。谢谢。

【问题讨论】:

  • API 对编码的要求是什么?看起来他们需要 JSON 内容,所以我首先尝试确保将其设置为请求 body 而不是参数,并为 Content-Type 指定 text/jsontext/html 跨度>
  • 我刚刚检查过了。 API 要求数据是原始的,而不是 JSON。如何通过向 API 发送原始字符串来发出 POST 请求?

标签: ios json xcode post


【解决方案1】:

您可以尝试下面的代码。而不是将数据转换为字符串,而是将其设置为 HTTPBody 之类的

// Create the request.
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

// Specify that it will be a POST request
request.HTTPMethod = @"POST";

// This is how we set header fields
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];


// Convert your data and set your request's HTTPBody property

NSArray *objects = [[NSArray alloc] initWithObjects:@"",@"3e708bf1a49cdd06",@"abc@xyz.in",@"abc",@"1234567890",@"true", nil];

NSArray *keys = [[NSArray alloc] initWithObjects:@"auth_token",@"device_id",@"email_address",@"name",@"number",@"resend_token", nil];

NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];

NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,@"customer", nil];

NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];


request.HTTPBody = temp;


// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:@"POST"];
 [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

【讨论】:

  • * request.HTTPBody = temp 是唯一的变化。这工作得很好,谢谢。 [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 是我丢失的关键。
【解决方案2】:
NSString *post =[[NSString alloc] initWithFormat:@"id=%d&restaurant_name=%@", restaurnt_Id, _rest_NameTxt.text];
    NSLog(@"PostData: %@",post);

NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"APPLICATION/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"APPLICATION/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

_responseData = [[NSMutableData alloc] init];

[NSURLConnection connectionWithRequest:request delegate:self];

pragma mark - 连接方法

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

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_responseData appendData:data];
    [_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return YES;
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [COMMON showErrorAlert:@"Internet Connection Error!"];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    responseString = [responseString stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    NSLog(@"%@", responseString); 
}

在 connectionDidFinishLoading 方法中完成你的任务

【讨论】:

    【解决方案3】:

    以下是向服务器发送 POST 请求的示例代码。

    -(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
        requestDic = [NSDictionary dictionaryWithDictionary:data];
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
        NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
    
        NSLog(@"Request Object:\n%@\n",data);
        NSLog(@"Request String:\n%@\n",jsonString);
    
        NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
        [theReq addValue: @"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [theReq setHTTPMethod:@"POST"];
        [theReq addValue:[NSString stringWithFormat:@"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:@"Content-Length"];
        [theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
        connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
    }
    

    希望这对您有很大帮助并解决您的问题。

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 2016-08-02
      • 2016-09-03
      • 1970-01-01
      相关资源
      最近更新 更多