NSURLSession 如何使用

我正在尝试发送一个 Post 请求来登录服务。我已经用 NSURLConnection 做到了这一点,但是后来发现它被弃用了,所以我尝试切换到 NSURLSession,但我不知道该怎么做,也不知道为什么我的代码不起作用。请注意,由于安全原因,一些代码已被删除。

我在控制台上看到了这个:

2015-12-24 15:04:35.624 [21173:761903] SUCESS
2015-12-24 15:04:36.445 [21173:762056] response is <NSHTTPURLResponse: 0x7f8f3d0bd9d0> { URL: https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession&api_key=apikey&format=json&username=username&password=password&api_sig=apisig } { status code: 400, headers {
"Access-Control-Allow-Methods" = "POST, GET, OPTIONS";
"Access-Control-Allow-Origin" = "*";
"Access-Control-Max-Age" = 86400;
Connection = "keep-alive";
"Content-Length" = 58;
"Content-Type" = "application/json";
Date = "Thu, 24 Dec 2015 15:04:35 GMT";
Server = "openresty/1.7.7.2";
} }
点赞
用户771231
用户771231

这行代码并不正确用于发送 post 请求。

NSString *post = [NSString stringWithFormat:@"https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession&api_key=apikey&format=json&username=%@&password=%@&api_sig=%@", username, password, [api_sig md5]];

你应该将你的 URL 与查询分离,然后将查询作为数据 post 到请求体中。

可以像这样:

NSURL * url = [NSURL URLWithString:@"https://ws.audioscrobbler.com/2.0/"];
NSString * post = [NSString stringWithFormat:@"method=auth.getMobileSession&api_key=someapikey&format=json&username=%@&password=%@&api_sig=%@", username, password, [api_sig md5]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];
2015-12-24 15:22:04