【问题标题】:NSURLSession post request not workingNSURLSession 发布请求不起作用
【发布时间】:2016-07-12 09:21:01
【问题描述】:

我正在尝试通过NSURLSession 访问我的帖子网络服务,但它返回错误 405,即找不到(方法)。但是当我通过NSURLConnection 访问它时它工作正常。下面是代码。

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURL *url = [NSURL URLWithString:@"web service url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];



[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"en", @"language",
                         nil];

NSLog(@"%@",url);
NSLog(@"%@",mapData);

NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];


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

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);
    NSLog(@"%ld",(long)error.code);

    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);

}];

[postDataTask resume];

【问题讨论】:

  • 请添加错误详情。
  • 错误说明??

标签: ios objective-c post nsurlconnection nsurlsession


【解决方案1】:

在您的代码中添加以下行:

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

【讨论】:

  • 请跳过401描述。
  • ttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" rel="nofollow" target="_blank">w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > w3.org/1999/xhtml"> Service
    html>
  • 您的服务是 XML 格式的吗?
  • 401 是这个响应代码而不是错误代码。这就是我得到的回应。
  • {"Message":"处理请求时出错。","StackTrace":"","ExceptionType":""}
  • 猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2019-01-27
    • 2017-01-28
    • 2017-08-20
    相关资源
    最近更新 更多