Java_HttpClientUtil

Java发送HTTP请求访问接口:

HttpClient 是apache 组织下面的一个用于处理HTTP 请求和响应的开源工具

1、HTTP-REQUEST-GET

/**
     * HTTP-REQUEST-GET
     * @param url
     * @param dataMap
     * @return
     */
    public static String sendGetHttpRequest(String url, Map<String, String> dataMap){

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String param = "";
        String content = "";
        try {
            httpClient = HttpClients.createDefault();
            if(null != dataMap && !CollectionUtils.isEmpty(dataMap.keySet())){
                StringBuffer bufParam = new StringBuffer();
                for (String key : dataMap.keySet()) {
                    bufParam.append(key+"=").append(dataMap.get(key)).append("&");
                }
                param = bufParam.subSequence(0, bufParam.length()-1).toString();

                StringBuffer urlParam = new StringBuffer();

                urlParam.append(url).append("?").append(param);

                url = urlParam.toString();
            }

            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

            HttpEntity httpEntity = httpResponse.getEntity();

            content = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));

        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                httpResponse.close();
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return content;
    }

2、HTTP-REQUEST-POST

 /**
     * HTTP-REQUEST-POST
     * @param url
     * @param dataMap:传参
     * @return
     */
    public static String sendPostHttpRequest(String url, Map<String, String> dataMap){

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (String key : dataMap.keySet()) {
            formparams.add(new BasicNameValuePair(key, dataMap.get(key)));
        }

        CloseableHttpResponse httpResponse = null;
        String content = "";
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

            httpPost.setEntity(entity);

            httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

            content = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;

    }

3、HTTP-REQUEST-UPLOAD(参数是个文件)

 /**
     * 上传文件
     * 
     */
    private static void upload(String url, File file, Map<String, Object> dataMap) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
        httpPost.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
        httpPost.setHeader("Connection", "keep-alive");

        FileBody fileBody = new FileBody(file);

        String data = JSON.toJSONString(dataMap);
        StringBody stringBody1 = new StringBody(data, ContentType.MULTIPART_FORM_DATA);

        try {
            HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("filename", fileBody).addPart("data", stringBody1).setCharset(CharsetUtils.get("UTF-8"))
                    .build();

            httpPost.setEntity(entity);
            CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();
            HttpResponse httpResponse;
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String content = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
            JSONObject result = JSONObject.parseObject(content);
            if (result == null ) {
                throw new Exception("上传文件失败,返回数据为:" + content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注释:1、Accept-Language 是HTTP 请求里面的一个属性,用于告诉服务器浏览器可以支持什么语言。如果网站支持多语种的话,可以使用这个信息来决定返回什么语言的网页 。zh-CN 是表示中文,fr-FR 是表示法语
2、请求头Accept-Charset 是告诉服务器,客户端提交的表单使用的编码。与服务器的响应内容编码无关。而响应头Content-Type 中的 charset则将告诉浏览器,服务器返回的文本采用什么编码
Connection:keep-alive长连接,需要服务端支持。同时Keep-Alive不会永久保持连接,它有一个保持时间,可以在不同的服务器软件(如Apache)中设定这个时间

4、发送HTTP请求并携带Cookie

/**
     * HTTP-REQUEST-GET
     * @param url
     * @param dataMap
     * @param cookie 身份认证
     * @return
     */
    public static String sendGetHttpRequest(String url, Map<String, String> dataMap, String cookie) {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String param = "";
        String content = "";
        try {
            httpClient = HttpClients.createDefault();
            if(null != dataMap && !CollectionUtils.isEmpty(dataMap.keySet())){
                StringBuffer bufParam = new StringBuffer();
                for (String key : dataMap.keySet()) {
                    bufParam.append(key+"=").append(dataMap.get(key)).append("&");
                }
                param = bufParam.subSequence(0, bufParam.length()-1).toString();

                StringBuffer urlParam = new StringBuffer();

                urlParam.append(url).append("?").append(param);

                url = urlParam.toString();
            }

            HttpGet httpGet = new HttpGet(url);

            httpGet.addHeader("Cookie", cookie);

            httpResponse = httpClient.execute(httpGet);

            HttpEntity httpEntity = httpResponse.getEntity();

            content = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));

        } catch (Exception e) {
            throw new BizException(null,"HTTP GET请求发生异常",e);
        } finally{
            try {
                httpResponse.close();
                httpClient.close();
            } catch (Exception e) {
                throw new BizException(null,"资源释放发生异常",e);
            }
        }
        return content;
    }

MAVEN依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcomponents-client</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>        
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.2</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java常用的Httpclient工具是HttpclientUtilHttpclientUtil是一个基于Apache HttpClient组件封装的工具类,它提供了简洁的接口和方法,使得Java开发者可以轻松地进行HTTP请求的发送和接收。 HttpclientUtil的主要特点和用途包括以下几个方面: 1. 发送HTTP请求:HttpclientUtil提供了get和post两种发送HTTP请求的方法,开发者可以根据需要选择合适的方法。发送请求时,可以设置请求头、请求参数、超时时间等。 2. 接收HTTP响应:HttpclientUtil能够接收HTTP响应,并对响应进行处理。开发者可以通过获取响应头、响应体等信息,实现对响应的解析和处理。 3. 支持HTTPS:HttpclientUtil对HTTPS请求也提供了支持,可以实现HTTPS请求的发送和接收。同时,也支持自定义HTTPS证书的配置,提高了安全性。 4. 连接池管理:HttpclientUtil使用连接池来管理HTTP连接,可以有效地提高请求的性能和效率。连接池可以复用已经建立的连接,减少了连接的建立和关闭的次数。 5. 支持cookie管理:HttpclientUtil能够自动管理请求和响应中的cookie信息,简化了开发者对cookie的处理过程。 6. 异步请求:HttpclientUtil支持异步请求,可以实现并发发送多个HTTP请求,并对响应进行处理。 总的来说,HttpclientUtil是一个功能强大、使用简便的Httpclient工具类,它方便了Java开发者进行HTTP请求的发送和接收,并提供了丰富的功能和选项,以满足不同的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值