【问题标题】:Post request with raw body using NSURLSession使用 NSURLSession 使用原始正文发布请求
【发布时间】:2015-12-17 06:24:22
【问题描述】:

我卡在这里了。下面是我使用 NSURLSession 使用原始正文的 Post 请求的代码。我得到了 response = NULL 并且没有错误。

NSString* stringRequest = @"https://chocudan.com/api/shops/by_ids";
NSURL* urlRequest = [NSURL URLWithString:stringRequest];

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:urlRequest];
request.HTTPMethod = @"POST";

NSString* bodyRequest = @"563c268b84ba489c4729f149";

//I have to tried a base64 convert here but still not work.
//request.HTTPBody = [NSData base64DataFromString:bodyRequest];

request.HTTPBody = [bodyRequest dataUsingEncoding:NSUTF8StringEncoding];


NSURLSessionConfiguration* configureSession = [NSURLSessionConfiguration defaultSessionConfiguration];

configureSession.HTTPAdditionalHeaders = @{@"Content-Type" : @"application/json charset=utf-8",
                                           @"Content-Lenght" : @"180"};

NSURLSession* session = [NSURLSession sessionWithConfiguration:configureSession];

NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;

    if (!error && respHttp.statusCode == 200) {

        NSDictionary* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

        NSLog(@"%@", respondData);
    }else{

        NSLog(@"%@", error);
    }

}];

[dataTask resume];

我必须尝试使用​​邮递员,一切正常。这是图片。

提前致谢。

【问题讨论】:

    标签: ios objective-c nsurlsession


    【解决方案1】:

    也换个试试

        NSArray* bodyArray = @[@"563c268b84ba489c4729f149"]
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bodyArray 
              options:NSJSONWritingPrettyPrinted error:&error];
       request.HTTPBody = jsonData;
    

    【讨论】:

    • 然后它变成了一个 NSArray,当我要改变一切时它仍然是一样的
    • 那是正确的......您需要传递 nsarray 并使用 NSJSONSerialization.dataWithJSONObject 将其转换为 nsdata
    • 对不起,我不明白你的意思。当我想从响应中获取 Json 时,为什么我们使用 NSJSONSerialization.dataWithJSONObject ?
    • 因为你想将数据作为 body 传递......并且 body 的格式是数组结构......所以你需要创建数组......但是 httpbody 需要 NSData 以便将你的数组转换为 NSData '将使用 dataWithJSONObject 方法
    • 我已经更新了我的答案...看看你能不能明白我在说什么
    【解决方案2】:

    我的原始数据是这样的:

    {
    "email":"test@gmail.com",
    "password":"12345678"
    }
    

    而我所做的是:

    NSMutableDictionary *dict  = [[NSMutableDictionary alloc] init];
    [dict setValue:@"test@gmail.com" forKey:@"email"];
    [dict setValue:@"12345678" forKey:@"password"];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                      options:NSJSONWritingPrettyPrinted error:&error];
                      request.HTTPBody = jsonData;
    

    【讨论】:

      【解决方案3】:

      这为我解决了问题:

      let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
          configuration.HTTPAdditionalHeaders = ["Content-Type" : "text/plain"]
      

      【讨论】:

      • 我必须解决我的问题,但稍后我会尝试您的解决方案。谢谢。
      • 查看他的邮递员示例。内容是 json 类型,而不是文本。但是,内容类型必须是服务器处理的内容。不要期望 API 会自动完成所有工作。 :-)
      【解决方案4】:

      我猜不是数据为空,而是respondData 为空?

      这是因为您的服务发送了一个包含一个对象的数组。 JSONSerialisation 从其中创建一个NSArray,其中包含一个NSDictionary。字典有键 _idcontact 等等。

      原来如此

      NSArray* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
      

      顺便说一句

       NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;
      

      没有多大意义,但也无害。

      关于您的请求正文,请参阅 mihir 的回答。他是对的。 当你这样做时,它可能会帮助你理解 mihir 的观点:

      NSString* bodyRequest = @"[563c268b84ba489c4729f149]";
      

      但是,这相当快速和肮脏,但可以帮助您理解这些原则。一旦了解,您一定会遵循米希尔的建议。

      【讨论】:

        【解决方案5】:

        如果要发布raw,并且param是NSString的格式,只需要这样做:

        NSData *param_data = [encry_str dataUsingEncoding:NSUTF8StringEncoding];
        murequest.HTTPBody = param_data;
        

        如果我们无法从该响应中获得任何信息,请注意响应序列化程序是正确的。任何额外的设置,请与服务器处理。

        【讨论】:

          猜你喜欢
          • 2021-03-04
          • 1970-01-01
          • 2018-11-10
          • 2013-10-06
          • 1970-01-01
          • 1970-01-01
          • 2017-01-23
          • 2019-01-07
          • 2013-09-13
          相关资源
          最近更新 更多