HttpClient3和HttpClient4性能比较

把这个帖子作为日记,记下来,如果title带有为什么,Javaeye会自动把它移到问答频道,重新输入一下,看看高手们的反应:

 

最近为了查一个问题,分别使用HttpClient3和HttpClient4发一个同样post请求到同一个server上,发现 HttpClient3比HttpClient4性能要好很多,测试结果是H3,平均时间是800ms,而httpClient4要3秒钟,代码如下:

 

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.DefaultMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

 

/*

* @author Tomy Zhou
 * @since 1.0
 * @version ; HttpClientTest.java 2010-7-6
 **/
public class HttpClientTest {

    public static void main(String[] args) throws Exception {

        /***************************************
         *
         * Method1
         *
         * Using HttpClient3
         *
         *
         *
         *
         */
        long startTime = System.currentTimeMillis();
        NameValuePair[] postData = new NameValuePair[1];
        postData[0] = new NameValuePair("hl", "zh-CN");

        PostMethod post = new PostMethod("http://www.google.com.hk/search");

        HttpClient client = new HttpClient();

        int httpStatusCode = -1;
        InputStream in = null;
        // Set RetryHandler
        DefaultMethodRetryHandler retryhandler = new DefaultMethodRetryHandler();
        retryhandler.setRequestSentRetryEnabled(true);
        retryhandler.setRetryCount(3);
        post.setMethodRetryHandler(retryhandler);
        // Set Post Data
        post.setRequestBody(postData);
        BufferedReader ins = null;
        String loginResult = null;
        // Execute Post Request
        try {
            // (client.getHttpConnectionManager()).closeIdleConnections(0);
            httpStatusCode = client.executeMethod(post);
            in = post.getResponseBodyAsStream();
            ins = new BufferedReader(new InputStreamReader(in, "ISO-8859-1"));
            String line = null;
            StringBuffer outbuffer = new StringBuffer();
            while ((line = ins.readLine()) != null) {
                outbuffer.append(line);
            }
            loginResult = outbuffer.toString();
            System.out.println(loginResult);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (ins != null) {
                ins.close();
            }
            if (post != null) {
                post.releaseConnection();
                // (client.getHttpConnectionManager()).closeIdleConnections(0);
            }
        }
        System.out.println("The httpClient3 duration is ======"
                + (System.currentTimeMillis() - startTime));
        /*******************************************************************
         *
         *
         *Using HttpClient4 method1 to test
         *
         *
         */
        startTime = System.currentTimeMillis();
        DefaultHttpClient httpclient = new DefaultHttpClient();

        // 目标地址
        HttpPost httppost = new HttpPost("http://www.google.com.hk/search");
        // 构造最简单的字符串数据
        StringEntity reqEntity = new StringEntity("hl=zh-CN");

        // 设置请求的数据
        httppost.setEntity(reqEntity);
        // 执行
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        System.out.println("----------------------------------------");

        // 显示结果
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(entity
                    .getContent(), "UTF-8"));
            String line = null;
            StringBuffer outbuffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                outbuffer.append(line);
            }
            System.out.println(outbuffer);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        httpclient.getConnectionManager().shutdown();
        System.out.println("The httpClient4 duration is ======"
                + (System.currentTimeMillis() - startTime));
        Thread.sleep(10000);

        /*******************************************************************
         *
         *
         *Using HttpClient4 method2 to test
         *
         *
         */
        startTime = System.currentTimeMillis();
        // 3.Use HttpClient4 - 2
        DefaultHttpClient httpclient2 = new DefaultHttpClient();

        // 目标地址
        HttpPost httppost2 = new HttpPost("http://www.google.com.hk/search");
        // 构造最简单的字符串数据
        List<org.apache.http.NameValuePair> formParams = new ArrayList<org.apache.http.NameValuePair>();
        formParams.add(new BasicNameValuePair("hl", "zh-CN"));
        HttpEntity entityForm = new UrlEncodedFormEntity(formParams, "UTF-8");

        // 设置请求的数据
        httppost2.setEntity(entityForm);
        // 执行
        HttpResponse response2 = httpclient2.execute(httppost);
        HttpEntity entity2 = response2.getEntity();
        System.out.println("----------------------------------------");

        // 显示结果
        BufferedReader reader2 = new BufferedReader(new InputStreamReader(
                entity2.getContent(), "UTF-8"));
        String line2 = null;
        StringBuffer outbuffer2 = new StringBuffer();
        while ((line2 = reader2.readLine()) != null) {
            outbuffer2.append(line2);
        }
        System.out.println(outbuffer2);
        httpclient2.getConnectionManager().shutdown();
        System.out.println("The httpClient4-2 duration is ======"
                + (System.currentTimeMillis() - startTime));

    }

}

 

请大家赐教,什么原因造成这么大的差别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[2\]中提到,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,提高了开发的效率和代码的健壮性。而引用\[3\]中提到,RestTemplate默认依赖JDK提供的HttpURLConnection,但也可以通过设置HttpRequestFactory的方式集成其他Http客户端。因此,HttpClient和RestTemplate在性能上可能存在一些差别。 然而,具体的性能差别取决于多个因素,如网络环境、请求的复杂性、服务器的响应速度等。一般来说,HttpClient性能方面可能更优秀,因为它提供了更多的功能和灵活性,可以更好地处理复杂的请求和响应。而RestTemplate则更适合简单的HTTP请求和响应。 总的来说,如果你需要处理复杂的HTTP请求和响应,或者对性能有较高的要求,使用HttpClient可能更合适。而如果你只需要进行简单的HTTP请求和响应,或者希望与Spring框架更好地集成,使用RestTemplate可能更方便。最终的选择应该根据具体的需求和场景来决定。 #### 引用[.reference_title] - *1* *2* [HttpClient和RestTemplate总结](https://blog.csdn.net/qq_38917188/article/details/116757134)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [HttpClient & RestTemplate](https://blog.csdn.net/weixin_44641388/article/details/121515758)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值