美文网首页
HttpClient的基本使用

HttpClient的基本使用

作者: 木果渣 | 来源:发表于2018-04-17 22:29 被阅读0次
      最近在调http接口,那天同事小哥突然跑过来跟我说,到时候线上的接口地址都是https的哦,你要不要准备两套代码。我???(((φ(◎ロ◎;)φ)))有什么不一样嘛???
      我只晓得https协议加了个证书,对传输的数据进行了加密,但是我以前调了那么多接口都是https地址的,也是一套代码啊。后来老大跟我说,httpClient已经封装的很好了,http和https地址都是同时支持的,除非那种用自己私有证书的,比如12306那种,你打开网页的时候就让你下个证书的网站,才需要特殊处理。━((*′д`)爻才发现以前自己根本没注意过这个问题,所以就把httpClient的基本方法重新写了一遍,可以适合大部分的请求。至于http和https的区别以及https的特殊处理或者说两者的原理区分,以后再写(其实,我再毕业那年面试的时候就被问过这个问题,然而我到现在还是喵喵喵???)。
    

    使用的包

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

    一个简单的httpClient实例

    public class SimpleClient {
    
        /**
         * 普通get请求
         * http https 通用
         *
         * @param url
         * @return
         */
        public static String doSimpleGet(String url) {
            //httpClient 4.0新写法
            CloseableHttpClient httpclient = HttpClients.createDefault();
            // 设置代理服务器地址和端口
            HttpGet httpGet = new HttpGet(url);
    
            //超时设置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)    //设置连接超时时间,单位毫秒。
                    .setConnectionRequestTimeout(1000)  //设置从connect Manager获取Connection 超时时间,单位毫秒。 从httpClient连接池获取httpClient
                    .setSocketTimeout(5000)     //请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
                    .build();
    
            httpGet.setConfig(requestConfig);
    
            CloseableHttpResponse response = null;
            String rst = null;
            try {
                response = httpclient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();/** 返回状态 **/
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        rst = EntityUtils.toString(entity, HTTP.UTF_8);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return rst;
        }
    
        /**
         * @param url
         * @param params 参数 ?a1=123&a2=321
         * @return
         */
        public static String doParamsGet(String url, Map<String, String> params) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            //创建一个uri对象
            URIBuilder uriBuilder = null;
    
            CloseableHttpResponse response = null;
            String rst = null;
            try {
                uriBuilder = new URIBuilder(url);
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    uriBuilder.addParameter(entry.getKey(), entry.getValue());
                }
                HttpGet httpGet = new HttpGet(uriBuilder.build());
                response = httpclient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();/** 返回状态 **/
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        rst = EntityUtils.toString(entity, HTTP.UTF_8);
                    }
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return rst;
        }
    
        /**
         * 普通post请求
         * 直接post json
         *
         * @param url
         * @param json
         * @return
         */
        public static String doPostJson(String url, String json) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String rst = null;
    
            // 请求地址
            HttpPost httpPost = new HttpPost(url);
    
            //post请求
            try {
                httpPost.addHeader("Content-type", "application/json; charset=utf-8");
                httpPost.setHeader("Accept", "application/json");
                httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
                response = httpclient.execute(httpPost);
    
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        rst = EntityUtils.toString(entity, HTTP.UTF_8);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return rst;
        }
    
        /**
         * post 表单
         *x-www-form-urlencoded
         * @param url
         * @param params
         * @return
         */
        public static String doPostForm(String url, Map<String, Object> params) {
            String rst = null;
    
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
    
            try {
                // 请求地址
                HttpPost httpPost = new HttpPost(url);
    
                List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
                httpPost.setEntity(urlEncodedFormEntity);
    
                //x-www-form-urlencoded
                //urlEncodedFormEntity.getContentType()
    
                response = httpclient.execute(httpPost);
    
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        rst = EntityUtils.toString(entity, HTTP.UTF_8);
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return rst;
        }
    }
    

    可以上传和下载文件的httpClient

    public class MultiClient {
    
    
        /**
         * 上传文件
         *
         * @param url
         * @param fileName
         * @return
         */
        public static String uploadFile(String url, String fileName) {
            String rst = null;
            CloseableHttpClient httpclient = HttpClients.createDefault();
    
            File file = new File(fileName);
            String message = "This is a multipart post";
    
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addBinaryBody("mFile", file, ContentType.DEFAULT_BINARY, fileName);
            builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
            HttpPost post = new HttpPost(url);
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            try {
                HttpResponse response = httpclient.execute(post);
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("<<<<<<<<<code<<<<<" + statusCode);
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    if (responseEntity != null) {
                        rst = EntityUtils.toString(responseEntity, HTTP.UTF_8);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return rst;
        }
    
        /**
         * 下载文件
         *
         * @param url
         */
        public static void downloadFile(String url, String fileName) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url + "?fileName=" + fileName);
            CloseableHttpResponse response = null;
            BufferedOutputStream out = null;
            try {
                response = httpclient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        byte[] rsts = EntityUtils.toByteArray(entity);
    
                        File file = new File("d:/tmp/downloadFile");
                        if (!file.exists()) {
                            file.createNewFile();
                        }
    
                        out = new BufferedOutputStream(new FileOutputStream(file));
                        out.write(rsts);
    
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (httpclient != null) {
                        httpclient.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    

    以上http请求适用的接口

    @RestController
    @RequestMapping("/http")
    @Slf4j
    public class HttpController {
    
        @RequestMapping(value = "/getParam", method = RequestMethod.GET)
        public String getParam(@RequestParam String data, @RequestParam Integer code) {
            return data + "-new";
        }
    
        @RequestMapping(value = "/postJson", method = RequestMethod.POST)
        public Book postJson(@RequestBody Book book) {
            book.setName("new-" + book.getName());
            book.setNum(book.getNum() + 1);
            return book;
        }
    
        @RequestMapping(value = "/postForm", method = RequestMethod.POST)
        public String postForm(@RequestParam String data, @RequestParam Integer code) {
            return data + code;
        }
    
        @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
        public String uploadFile(@RequestParam("mFile") MultipartFile mFile, @RequestParam("text") String text) {
            String content = null;
            try {
                byte[] buffer = mFile.getBytes();
                content = new String(buffer, "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return content + "\n" + text;
        }
    
        @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
        public void downloadFile(@RequestParam String fileName, HttpServletResponse response) {
            File file = new File("d:/" + fileName + ".png");
            response.setContentType("image/png");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Access-Control-Allow-Origin", "*");
    
            ServletOutputStream out = null;
            BufferedInputStream in = null;
    
            try {
                in = new BufferedInputStream(new FileInputStream(file));
                out = response.getOutputStream();
    
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                out.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    
    

    后续还要写个需要登陆的httpClient

    相关文章

      网友评论

          本文标题:HttpClient的基本使用

          本文链接:https://www.haomeiwen.com/subject/seqmkftx.html