ios - NSURLSession 操作方法
<p><p>我正在尝试发送发布请求以登录服务。我让它与 NSURLConnection 一起工作,但后来发现它已被贬值,所以我尝试切换到 NSURLSession,但我不知道该怎么做或为什么我的代码不起作用。请注意,出于安全原因,部分代码已被删除。</p>
<pre><code>-(NSString *)signIn:(NSString *)username password:(NSString *)password{
NSString *api_sig = ;//API signature
NSString *post = ];
NSMutableURLRequest *request =
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLSessionConfiguration *configuration = ;
NSURLSession *session = ;
;
];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"response is %@", response);
}];
;
if (session) {
NSLog(@"SUCESS");
}else{
NSLog(@"FAILURE");
}
return nil;
}
-(void)URLSession:(NSURLSession *)session dataTask: (NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
NSLog(@"data is %@", data);
}
</code></pre>
<p>我在控制台中得到这个</p>
<pre><code>2015-12-24 15:04:35.624 SUCESS
2015-12-24 15:04:36.445 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";
} }
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这行代码不适合post。</p>
<pre><code>NSString *post = ];
</code></pre>
<p>您应该将您的网址与查询分开,然后将查询作为数据发布到正文。 </p>
<p>类似:</p>
<pre><code>NSURL * url = ;
NSString * post = ];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
</code></pre></p>
<p style="font-size: 20px;">关于ios - NSURLSession 操作方法,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/34454714/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/34454714/
</a>
</p>
页:
[1]