iOS中的Android okhttp相当于什么?

时间:2016-05-31 00:18:40

标签: android ios nsurlconnection okhttp

Android来源

String url = "http://www.example.com";
OkHttpClient client = clientBuilder.build();
Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Host", "api.example.com")
                    .addHeader("Referer", "http://www.examplegood.com/")
                    .build();

Response response = client.newCall(request).execute();

效果很好。我在iOS中尝试使用NSURLConnection请求。

iOS来源

NSString *url = @"http://www.example.com";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setValue:@"api.example.com" forHTTPHeaderField:@"Host"];
[request setValue:@"http://www.examplegood.com/" forHTTPHeaderField:@"Referer"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod: @"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                NSMutableData *result = [[NSMutableData alloc] init];
                [result appendData:data];

                NSString* resultStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
                NSLog(@"result:%@",resultStr);
            }];

效果不好。没有回应。 iOS中的Android OkHttpClient newCall()相当于什么?

1 个答案:

答案 0 :(得分:1)

我使用NSURLConnection解决了这个问题。并获得该代表的响应数据。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response