HttpClient如何在Java代码中发送与接收请求

前言:本文为原创 若有错误欢迎评论!

1.依赖

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.2.1</version>
    </dependency>

    <!-- 用来解析Json数据 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>

    <!-- 常用的工具类 如StringUtil -->
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>

2.HttpUtils代码

    /*
    * @param host:必须为"localhost:8080" 这种格式 有方法会补上http://
    * @param path:ip后面的相对路径 /api/v1/add
    *         注意:在buildUrl()拼接路径时 根据 host + path + "?" + querys(即没有补"/" )所以注意"/"的使用
    * @param method:请求方式 "GET" "POST" "PUT" "DELETE"
    * @param headers:请求头的信息 不可以为null 可以是空的Map
    * @param querys:适用于get和delete方式 在路径中带的请求的参数
    * @param bodys: post和put方式的请求数据
    *         可以解析成一个json字符串放入Request 客户端用@RequestBody接收 或者用Map<Stirng,Stirng>
    */
    public class HttpUtils {

        /**
        * get
        */
        public static HttpResponse doGet(String host, String path, String method,
            Map<String, String> headers,
            Map<String, String> querys)
            throws Exception {
                HttpClient httpClient = wrapClient(host);
    
                HttpGet request = new HttpGet(buildUrl(host, path, querys));
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }

                return httpClient.execute(request);
        }

        /**
        * post form
        */
        public static HttpResponse doPost(String host, String path, String method,
            Map<String, String> headers,
            Map<String, String> querys,
            Map<String, String> bodys)
            throws Exception {
                HttpClient httpClient = wrapClient(host);

                HttpPost request = new HttpPost(buildUrl(host, path, querys));
                for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
                }

                if (bodys != null) {
                    List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

                    for (String key : bodys.keySet()) {
                        nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
                    }
                    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
                    formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
                    request.setEntity(formEntity);
                }

                return httpClient.execute(request);
        }
    
        /**
        * Post String
        */
        public static HttpResponse doPost(String host, String path, String method,
            Map<String, String> headers,
            Map<String, String> querys,
            String body)
            throws Exception {
                HttpClient httpClient = wrapClient(host);

                HttpPost request = new HttpPost(buildUrl(host, path, querys));
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }

                if (StringUtils.isNotBlank(body)) {
                    request.setEntity(new StringEntity(body, "utf-8"));
                }

                return httpClient.execute(request);
        }

        /**
        * Post stream
        */
        public static HttpResponse doPost(String host, String path, String method,
            Map<String, String> headers,
            Map<String, String> querys,
            byte[] body)
            throws Exception {
                HttpClient httpClient = wrapClient(host);

                HttpPost request = new HttpPost(buildUrl(host, path, querys));
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }

                if (body != null) {
                    request.setEntity(new ByteArrayEntity(body));
                }

                return httpClient.execute(request);
        }

        /**
        * Put String
        */
        public static HttpResponse doPut(String host, String path, String method,
            Map<String, String> headers,
            Map<String, String> querys,
            String body)
            throws Exception {
                HttpClient httpClient = wrapClient(host);

                HttpPut request = new HttpPut(buildUrl(host, path, querys));
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }

                if (StringUtils.isNotBlank(body)) {
                    request.setEntity(new StringEntity(body, "utf-8"));
                }

               return httpClient.execute(request);
        }

        /**
        * Put stream
        */
        public static HttpResponse doPut(String host, String path, String method,
            Map<String, String> headers,
            Map<String, String> querys,
            byte[] body)
            throws Exception {
                HttpClient httpClient = wrapClient(host);

                HttpPut request = new HttpPut(buildUrl(host, path, querys));
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }

                if (body != null) {
                    request.setEntity(new ByteArrayEntity(body));
                }

                return httpClient.execute(request);
        }

        /**
        * Delete
        */
        public static HttpResponse doDelete(String host, String path, String method,
            Map<String, String> headers,
            Map<String, String> querys)
            throws Exception {
                HttpClient httpClient = wrapClient(host);

                HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }

                return httpClient.execute(request);
        }

        /*
        * 拼接请求路径
        */
        private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
            StringBuilder sbUrl = new StringBuilder();
            sbUrl.append(host);
            if(!StringUtils.isBlank(path)) {
                sbUrl.append(path);
            }
            if (null != querys) {
                StringBuilder sbQuery = new StringBuilder();
                for (Map.Entry<String, String> query : querys.entrySet()) {
                    if (0 < sbQuery.length()) {
                        sbQuery.append("&");
                    }
                    if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                        sbQuery.append(query.getValue());
                    }
                    if (!StringUtils.isBlank(query.getKey())) {
                        sbQuery.append(query.getKey());
                        if (!StringUtils.isBlank(query.getValue())) {
                            sbQuery.append("=");
                            sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                        }
                    }
                }
                if (0 < sbQuery.length()) {
                    sbUrl.append("?").append(sbQuery);
                }
            }

            return sbUrl.toString();
        }

        /*
        * 给host拼接"https://"
        */
        private static HttpClient wrapClient(String host) {
            HttpClient httpClient = new DefaultHttpClient();
            if (host.startsWith("https://")) {
                sslClient(httpClient);
            }

            return httpClient;
        }


        private static void sslClient(HttpClient httpClient) {
            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                X509TrustManager tm = new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] xcs, String str) {

                    }

                    public void checkServerTrusted(X509Certificate[] xcs, String str) {

                    }
                };
                ctx.init(null, new TrustManager[]{tm}, null);
                SSLSocketFactory ssf = new SSLSocketFactory(ctx);
                ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                ClientConnectionManager ccm = httpClient.getConnectionManager();
                SchemeRegistry registry = ccm.getSchemeRegistry();
                registry.register(new Scheme("https", 443, ssf));
            } catch (KeyManagementException ex) {
                throw new RuntimeException(ex);
            } catch (NoSuchAlgorithmException ex) {
                throw new RuntimeException(ex);
            }
        }

    }

3.解析HttpClient返回值

  • 请求返回的值会放在HttpEntity中
  • 必须要让返回的是json数据 如果返回的时xml格式页面的数据就不行
//先用EntityUtils解析成String类型 org.apache.http.util包下
String result = EntityUtils.toString(response.getEntity());

/* 
*方式1
*解析为jsonOject 一般不知道对象类型就使用这种方式 方法多比较灵活
*/
JSONObject jsonObject = JSON.parseObject(result);

//通过get取出Object里的值
Object value = jsonObject.get("key");

//如果有json的key对应的数组
JSONArray jsonArray = jsonObject.getJSONObject("name").getJSONArray("arrayName");
//迭代器模式 实现了iterator接口
//也可以使用for(int i=0;i<jsonArray.size();i++){ jsonArray.get(i)}
Iterator<Object> iterator = jsonArray.iterator();


/* 
 *方式2
*解析成Map对象 一般是为了遍历
*/
Map mapType = JSON.parseObject(result, Map.class);

for(Object object :mapType.keySet()){
    System.out.println("key为:" + object + "值为:" + mapType.get(object));
}
相关推荐
<p> <b><span style="font-size:14px;"></span><span style="font-size:14px;background-color:#FFE500;">【Java面试宝典】</span></b><br /> <span style="font-size:14px;">1、68讲视频课,500道大厂Java常见面试题+100个Java面试技巧与答题公式+10万字核心知识解析+授课老师1对1面试指导+无限次回放</span><br /> <span style="font-size:14px;">2、这门课程基于胡书敏老师8年Java面试经验,调研近百家互联网公司及面试官的问题打造而成,从筛选简历和面试官角度,给出能帮助候选人能面试成功的面试技巧。</span><br /> <span style="font-size:14px;">3、通过学习这门课程,你能系统掌握Java核心、数据库、Java框架、分布式组件、Java简历准备、面试实战技巧等面试必考知识点。</span><br /> <span style="font-size:14px;">4、知识点+项目经验案例,每一个都能做为面试的作品展现。</span><br /> <span style="font-size:14px;">5、本课程已经在线下的培训课程经过实际检验,老师每次培训结束后,都能帮助同学们运用面试技巧,成功找到更好的工作。</span><br /> <br /> <span style="font-size:14px;background-color:#FFE500;"><b>【超人气讲师】</b></span><br /> <span style="font-size:14px;">胡书敏 | 10年大厂工作经验,8年Java面试官经验,5年线下Java职业培训经验,5年架构师经验</span><br /> <br /> <span style="font-size:14px;background-color:#FFE500;"><b>【报名须知】</b></span><br /> <span style="font-size:14px;">上课模式是什么?</span><br /> <span style="font-size:14px;">课程采取录播模式,课程永久有效,可无限次观看</span><br /> <span style="font-size:14px;">课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化</span><br /> <br /> <br /> <span style="font-size:14px;background-color:#FFE500;"><strong>如何开始学习?</strong></span><br /> <span style="font-size:14px;">PC端:报名成功后可以直接进入课程学习</span><br /> <span style="font-size:14px;">移动端:<span style="font-family:Helvetica;font-size:14px;background-color:#FFFFFF;">CSDN 学院APP(注意不是CSDN APP哦)</span></span> </p>
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:马嘣嘣 返回首页