HttpClinent

基本用法

maven坐标:
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

get请求:

public static  void httpClientGetTest() throws URISyntaxException {
            //创建HttpClient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //无参url
            //HttpGet httpGet = new HttpGet("http://www.baidu.com");
            //有参url后面的addParameter,可以无限的追加不用使用&分割自动添加;

        URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com").addParameter("wd", "新闻");
        HttpGet httpGet = new HttpGet(uriBuilder.toString());
        try {
                //发起请求,获取结果
                CloseableHttpResponse response= httpClient.execute(httpGet);
                //返回值200为响应成功
                if (response.getStatusLine().getStatusCode() == 200) {
                    //获取响应实体
                    HttpEntity entity = response.getEntity();
                    //转码
                    String utf8 = EntityUtils.toString(entity, "utf8");
                    System.out.println(utf8);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

post 用法

public static void httpClientPostTest() throws UnsupportedEncodingException {

        //创建httpClient对象
        CloseableHttpClient aDefault = HttpClients.createDefault();

        //设置发送表单内容数据
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
        //使用NameValuePair的实现类添加键值对的参数 键值对格式
        nameValuePairs.add(new BasicNameValuePair("wd","音乐"));

        //创建表单entity对象就是封装好的参数的bean,前面是参数后面是编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, "utf8");
        //创建Post请求对象
        HttpPost httpPost = new HttpPost("http://www.baidu.com");

    }

还可以配置连接池,最长连接时间,最大访问主机...配置因为本人只需要简单的应用所以不展开
    ````
### 工具类
```java
package com.tbc.app.wx.util;

import com.google.gson.Gson;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

public class HttpUtils {

    public static final Gson gson = new Gson();

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPost(String url, Map<String, Object> paramMap) {
        Assert.hasText(url, "Url is empty!");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            if (MapUtils.isNotEmpty(paramMap)) {
                StringEntity entity = new StringEntity(gson.toJson(paramMap), "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            CloseableHttpResponse response = httpClient.execute(httpPost);
            String result;
            result = getString(response);

            return result;
        } catch (Exception e) {
            throw new RuntimeException("Exception occurred when send post request[url:" + url
                    + ",paramMap:" + paramMap + "]!", e);
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                //np
            }
        }
    }

    private static String getString(CloseableHttpResponse response) throws IOException {
        String result;
        try {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                throw new RuntimeException("Unexpected failure: " + statusLine.toString());
            }

            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
                EntityUtils.consume(resEntity);
            } else {
                result = null;
            }
        } finally {
            response.close();
        }
        return result;
    }

    public static String doGet(String url, boolean mobile) {
        Assert.hasText(url, "Url is empty!");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            if (mobile) {
                httpGet.setHeader("user-agent",
                        "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
            }

            CloseableHttpResponse response = httpClient.execute(httpGet);
            String result;
            result = getString(response);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("Exception occurred when send post request[url:" + url, e);
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                //np
            }
        }
    }

    public static String getRealRemoteAddress(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        return getRealRemoteAddress(remoteAddr, xForwardedFor);
    }

    public static String getRealRemoteAddress(String remoteAddr, String xForwardedFor) {
        if (StringUtils.isEmpty(remoteAddr) || remoteAddr.startsWith("127.")
                || remoteAddr.startsWith("10.") || remoteAddr.startsWith("192.")) {
            if (StringUtils.isNotEmpty(xForwardedFor)) {
                int pos = xForwardedFor.indexOf(',');
                if (pos == -1) {
                    remoteAddr = xForwardedFor.trim();
                } else {
                    remoteAddr = xForwardedFor.substring(0, pos).trim();
                }
            }
        }

        return remoteAddr;
    }
}

工具类用法:
```java
            JSONObject resultMap = (JSONObject) HttpClientUtils.httpGet(String.format(WxApiConstants.TOKEN, appId, secret));
            
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值