zoukankan      html  css  js  c++  java
  • HttpClient使用详解

    HttpClient的主要功能:

    • 实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
    • 支持 HTTPS 协议
    • 支持代理服务器(Nginx等)等
    • 支持自动(跳转)转向
    • 等等

    引入依赖

    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.5</version>
    </dependency>

    使用详解

    1. get方法

    public class GetUtils {

    //无参方式
    public void get(String url) {
    getWithParams(url, new HashMap<>());
    }

    //有参方式
    public void getWithParams(String url, Map<String, Object> params) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {
    // 创建Get请求
    url = joinParam(url, params);
    HttpGet httpGet = new HttpGet(url);
    RequestConfig requestConfig = RequestConfig.custom()
    .setSocketTimeout(2000) //服务器响应超时时间
    .setConnectTimeout(2000) //连接服务器超时时间
    .build();
    httpGet.setConfig(requestConfig);
    // 由客户端执行(发送)Get请求
    response = httpClient.execute(httpGet);
    // 从响应模型中获取响应实体
    HttpEntity responseEntity = response.getEntity();
    System.out.println("响应状态为:" + response.getStatusLine());
    if (responseEntity != null) {
    System.out.println("响应内容长度为:" + responseEntity.getContentLength());
    System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
    }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    // 释放资源
    if (httpClient != null) {
    httpClient.close();
    }
    if (response != null) {
    response.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    private static String joinParam(String url, Map<String, Object> params) {
    if (params == null || params.size() == 0) {
    return url;
    }

    StringBuilder urlBuilder = new StringBuilder(url);
    urlBuilder.append("?");

    int counter = 0;
    for (Map.Entry<String,Object> entry : params.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    if (key == null) {
    continue;
    }

    if (counter == 0) {
    urlBuilder.append(key).append("=").append(value);
    } else {
    urlBuilder.append("&").append(key).append("=").append(value);
    }
    counter++;
    }

    return urlBuilder.toString();
    }

    }

    2. post方法

    post请求有两种方式传参,一种是普通参数,一种是对象参数。普通参数传参方式和上面的get请求相同,对象参数需要使用setEntity()方法设置,同时需要指定请求的content-type

    以下两段代码均为对象方式传参

    2.1 content-type为:application/x-www-form-urlencoded

    public class PostUtils {
    
        public void post(String url) {
            postWithParams(url, new HashMap<>());
        }
    
        public void postWithParams(String url, Map<String, String> params) {
            List<NameValuePair> pairs = generatePairs(params);
    
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse response = null;
            try {
                HttpPost httpPost = new HttpPost(url);
                RequestConfig requestConfig = RequestConfig.custom()
                        .setSocketTimeout(2000) //服务器响应超时时间
                        .setConnectTimeout(2000) //连接服务器超时时间
                        .build();
                httpPost.setConfig(requestConfig);
    
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
                httpPost.setEntity(entity);
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                // 由客户端执行(发送)请求
                response = httpClient.execute(httpPost);
                System.out.println("响应状态为:" + response.getStatusLine());
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                    System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    // 释放资源
                    if (httpClient != null) {
                        httpClient.close();
                    }
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private List<NameValuePair> generatePairs(Map<String, String> params) {
            if (params == null || params.size() == 0) {
                return Collections.emptyList();
            }
    
            List<NameValuePair> pairs = new ArrayList<>();
            for (Map.Entry<String,String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (key == null) {
                    continue;
                }
    
                pairs.add(new BasicNameValuePair(key, value));
            }
    
            return pairs;
        }
    
    }

    2.1 content-type为:application/json

    public void postWithParams(String url, UserEntity userEntity) {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse response = null;
            try {
                HttpPost httpPost = new HttpPost(url);
                RequestConfig requestConfig = RequestConfig.custom()
                        .setSocketTimeout(2000) //服务器响应超时时间
                        .setConnectTimeout(2000) //连接服务器超时时间
                        .build();
                httpPost.setConfig(requestConfig);
    
                StringEntity entity = new StringEntity(JSON.toJSONString(userEntity), "utf-8");//也可以直接使用JSONObject
                httpPost.setEntity(entity);
                httpPost.setHeader("Content-Type", "application/json;charset=utf8");
                // 由客户端执行(发送)请求
                response = httpClient.execute(httpPost);
                System.out.println("响应状态为:" + response.getStatusLine());
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                    System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    // 释放资源
                    if (httpClient != null) {
                        httpClient.close();
                    }
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    其他

    提示:网上有很多开源的http工具类,Github上Star非常多的一个HttpClient的工具类是httpclientutil,该工具类的编写者封装了很多功能在里面,如果

               不是有什么特殊的需求的话,完全可以直接使用该工具类。使用方式很简单,可详见https://github.com/Arronlong/httpclientutil

  • 相关阅读:
    面向对象进阶
    EasyDSS转码模块关于gRPC服务注册到ETCD的实现过程
    如何通过ETCD实现EasyDSS分布式负载均衡?ETCD部署方案
    EasyDSS_dash版本如何在新内核下实现rtsp源地址的分发?
    EasyDSS因为系统时间导致的闪退分析及处理
    EasyScreenLive推流组件推RTSP流到EasyDSS操作过程分享
    【解决方案】无人机+EasyDSS实现直播推流警务安防类行业应用
    EasyDSS转码服务负载均衡采用grpc balance回报找不到结构体问题排查及修复
    EasyDSS视频直播时直播间接口和实际接口为什么会存在差异?
    在线课堂EasyDSS_dash版本虚拟直播RTSP播放无视频流问题
  • 原文地址:https://www.cnblogs.com/z-belief/p/11171822.html
Copyright © 2011-2022 走看看