HttpClient基础用法

一、HttpClient

    HttpClient是Apache HttpComponents 下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包(httpclient-4.4.1.jar)。HttpClient类可以用来发送Http请求(get,post,put,delete)相比传统JDK自带的URLConnection,增加了易用性和灵活性,如下为一个post类型的HTTP请求,参数列表中的header代表HTTP请求的header,params代表参数列表,body代表HTTP请求体

需要导入:import org.apache.http.client.HttpClients等
    public String post(String url,Map<String, String> header, Map<String, Object> params, Map<String, Object> entity, int soTimeout) {
        CloseableHttpClient httpclient = HttpClients.createDefault();  //创建一个httpclient
        HttpPost httppost = new HttpPost();  //创建一个httppost
        String result = null;
        try {
            //处理params,拼接url
            url = joinParam(url, params);  //根据需求自己实现该方法

            //add request url
            if (url != null) {
                httppost.setURI(URI.create(url));
            }

            //add header
            for (String key : header.keySet()) {
                httppost.addHeader(key, header.get(key));
            }

            //add entity
            if (entity != null) {
                String entityStr = toJSONString(entity);  //将map转化为string
                StringEntity stringEntity = new StringEntity(entityStr, "UTF-8");
                stringEntity.setContentType("text/json");
                stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                httppost.setEntity(stringEntity);
            }
            /**
             * setConnectTimeout:设置连接超时时间,单位毫秒。
             *setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
             *setSocketTimeout:请求获取数据的超时时间,单位毫秒。
             */
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(soTimeout).setConnectionRequestTimeout(soTimeout)
                    .setSocketTimeout(soTimeout).build();
            httppost.setConfig(requestConfig);

            CloseableHttpResponse response = null;
            try {
//发送post请求 response
= httpclient.execute(httppost); } catch (IOException e) { e.printStackTrace(); }
try { // 获取响post响应实体 if (response != null) { HttpEntity responseEntity = response.getEntity(); if(responseEntity != null) { result = responseEntity.toString(); if(responseEntity != null) { result = EntityUtils.toString(responseEntity); } } } } finally { if (response != null) { response.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }

 

 二、老版本HttpClient(commons-httpclient.jar)

    进入apache官网下找commons HttpClient包,可以看到一下描述:

The Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules, which offer better performance and more flexibility.

    可以看到commons-httpclient.jar已被httpclient.jar取代,官方不再提供commons-httpclient的更新维护服务。以下是使用老版本HttpClient发送一个post请求:

    需要导入:import org.apache.commons.httpclient.HttpClient等

    public String doPost(String url, Map<String, String> header, Map<String, Object> entity){
        String result = "";
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        try{
            //set header
            postMethod.addRequestHeader("Content-Type", "application/json");
            for (String key : header.keySet()) {
                postMethod.addRequestHeader(key, header.get(key));
            }

            //set entity
            String paramsStr = toJSONString(entity);
            RequestEntity requestEntity = new ByteArrayRequestEntity(paramsStr.getBytes("UTF-8"));
            postMethod.setRequestEntity(requestEntity);

            //get response
            int httpStatusCode = httpClient.executeMethod(postMethod);
            if (httpStatusCode < 200 || httpStatusCode >= 300) {
                throw new Exception("httpStatusCode is not correct! " + httpStatusCode);
            }
            result = IOUtils.toString(postMethod.getResponseBodyAsStream(), "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            postMethod.releaseConnection();
        }
        return result;
    }

 

转载于:https://www.cnblogs.com/z-belief/p/7550561.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值