hutool HttpRequest VS httpClient 到底哪个快
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StopWatch;
import cn.hutool.http.HttpRequest;
/**
* httpClient VS hutool HttpRequest
*
* @author douzi
* @date 2024-05-17
*/
public class Test2 {
public static void main(String[] args) {
System.out.println("httpClient VS hutool HttpRequest:");
StopWatch sw = new StopWatch();
sw.start();
String body = "";
for(int i = 0; i < 1000; i ++) {
body = HttpRequest.get("http://www.baidu.com")
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).timeout(3000)// 超时,毫秒
.execute().body();
}
sw.stop();
System.out.println("HttpRequest耗时:" + sw.getTotalTimeSeconds());
StopWatch sw1 = new StopWatch();
sw1.start();
for(int i = 0; i < 1000; i ++) {
HttpClient httpClient = new HttpClient();
HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
managerParams.setConnectionTimeout(3000); // 设置连接超时时间(单位毫秒)
managerParams.setSoTimeout(3000 * 2); // 设置读数据超时时间(单位毫秒)
GetMethod method = new GetMethod("http://www.baidu.com");
method.addRequestHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_OK) {
method.getResponseBodyAsString();
}
} catch(Exception e) {
} finally {
method.releaseConnection();
}
}
sw1.stop();
System.out.println("httpClient耗时:" + sw1.getTotalTimeSeconds());
}
}
hutool HttpRequest VS httpClient(1000次调用相同请求)测试结果:
HttpRequest耗时:14.6822173
httpClient耗时:24.140532