WebClient, HttpClient, OkHttp: 三个Java HTTP客户端的比较
warning:
这篇文章距离上次修改已过272天,其中的内容可能已经有所变动。
这三个Java HTTP客户端库都可以用来发送HTTP请求并处理响应。以下是各自的简单比较和示例代码:
- WebClient (Java 11及以上):
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class WebClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}
- HttpClient (Apache HttpComponents):
import org.apache.hc.client5.httpclient.HttpClientBuilder;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient client = builder.build();
HttpGet request = new HttpGet("http://example.com");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(EntityUtils.toString(entity));
}
}
- OkHttp (Square):
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpExample {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://example.com")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.code());
System.out.println(response.body().string());
}
}
这些示例都是同步执行的,如果需要异步执行,可以使用各自库提供的异步API。
评论已关闭