httpclient如何实现在一个连接中发送多次请求

public class Sample {

    private static ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse(
                final HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;

        }

    };

    public static String Get(CloseableHttpClient http, String url){
        HttpGet httpget = new HttpGet(url);


        System.out.println("Executing request " + httpget.getRequestLine());

        String html = "";

        try{
            html = http.execute(httpget, responseHandler);
        }finally{
            return html;
        }
    }

    public static void main(String[] args) throws Exception {
        CloseableHttpClient http = HttpClients.createDefault();
        try {
            Get(http, "http://www.qq.com/111.txt");
            Get(http, "http://www.qq.com/222.txt");
            Get(http, "http://www.qq.com/333.txt");
        } finally {
            http.close();
        }
    }
}

只有同一个网站,且支持 keepalive 的情况下,才可以用同一个连接.

使用的是 httpclient-4.5.1, 下载地址: http://mirrors.hust.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.5.1-bin.tar.gz

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您的问题是如何使用 HttpClient 发送 GET 请求并在 URL 后面拼接一个 ID? 您可以通过创建一个带有参数的 URI 对象来实现。首先,您需要创建一个 `HttpClient` 对象,然后创建一个 `HttpGet` 对象并设置请求的 URL。接下来,您可以使用 `URIBuilder` 来构建带有参数的 URI 对象,并将其设置为 `HttpGet` 对象的 URI。最后,您可以使用 `HttpClient` 对象来执行请求并获取响应。 以下是示例代码: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.HttpResponse; import java.net.URI; public class HttpClientExample { public static void main(String[] args) { String baseUrl = "http://example.com/api"; String id = "123"; try { URIBuilder builder = new URIBuilder(baseUrl); builder.setParameter("id", id); URI uri = builder.build(); HttpGet request = new HttpGet(uri); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); // 处理响应 } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码,我们创建了一个 `URIBuilder` 对象,并使用 `setParameter` 方法来设置 ID 参数。然后,使用 `build` 方法构建 URI 对象,并将其设置为 `HttpGet` 请求的 URI。最后,我们使用 `HttpClient` 对象来执行请求并获取响应。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值