简体   繁体   中英

What is the equivalent of Android okhttp in iOS?

Android Source

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();

It works well. I tried in iOS using NSURLConnection request.

iOS Source

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);
            }];

It works bad. There is no response. What is the equivalent of Android OkHttpClient newCall() in iOS?

I solved the problem using NSURLConnection. And get response data by this delegate.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM