httpClient

简介

官网:http://hc.apache.org/
使用场景:公司需要跟分子公司做数据交互,需要做服务端和客户端,首先考虑的就是http和webservice,这里选用http
jar包

        <!-- httpclient传送文件用的 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
        </dependency>

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

jdk原生api发送http请求

用原生的jdk请求一个http,然后获取它的源码输出

    @Test
    void test() throws Exception {
        String urlPath = "https://www.baidu.com/";
        //创建一个URL
        URL url = new URL(urlPath);
        //获取URL连接
        URLConnection urlConnection = url.openConnection();
        //要使用的是httpURL,强转一下
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        //设置请求类型,很多参数,需要的话可以设置
        /**
         * 请求行
         * 空格
         * 请求头
         * 请求体
         */
        httpURLConnection.setRequestMethod("GET");
        
        try (
                //    获取HttpURLConnection的输入流
                InputStream inputStream = httpURLConnection.getInputStream();
                //    请求的是网页,它的内容就是源代码,使用inputStreamReader
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                //    一行一行的读
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        ) {
            String line;
            //只要不为空,就输出当前行内容
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

        }


    }

httpclient

无参的get请求

    /**
     * httpclient发送get请求
     * 无参请求
     * @throws Exception
     */
    @Test
    void httpClientsTest() throws Exception {

        //CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        /*
            HttpClients是一个工具类,等同上面的方法
            可关闭的httpclient客户端,相当于打开的一个浏览器
         */
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        String urlPath = "https://www.baidu.com/";
        //httpGet
        HttpGet httpGet=new HttpGet(urlPath);
        
        //解决httpclient被认为不是真人行为(爬虫的应用,防止检测,可不设置)
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
        //防盗链,value必须为该网站的网址(爬虫的应用,可不设置)
        httpGet.addHeader("Referer","https://www.baidu.com/");

        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response=null;
        try {
            //发送请求
            response=closeableHttpClient.execute(httpGet);
            //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
            HttpEntity entity = response.getEntity();
            //对HttpEntity操作的工具类,转成string看下结果
            String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStringResult);
            //确保流关闭
            EntityUtils.consume(entity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (closeableHttpClient!=null){
                closeableHttpClient.close();
            }
            if(response!=null){
                response.close();
            }
        }


    }

有参的请求

对比无参的请求,只修改了一部分

        //如果字符中包含特殊字符或者空格会报错,需要处理一下
        String pwd="abcd+ |2312";
        //如果是浏览器,会自动帮我们处理,如果是httpclient请求,就需要手动处理,这里使用jdk处理
        pwd= URLEncoder.encode(pwd,StandardCharsets.UTF_8.name());

        String urlPath = "http://localhost:8080/login?userName="+username+"&passWord="+pwd;

以下是修改后的整体代码

    /**
     * httpclient发送get请求,测试自己写的接口
     * 有参请求,有些特殊字符,需要处理URLEncoder.encode
     *
     * @throws Exception
     */
    @Test
    void httpClientsController() throws Exception {

        //CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        /*
            HttpClients是一个工具类,等同上面的方法
            可关闭的httpclient客户端,相当于打开的一个浏览器
         */
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        String username="张三";
        //如果字符中包含特殊字符或者空格会报错,需要处理一下
        String pwd="abcd+ |2312";
        //如果是浏览器,会自动帮我们处理,如果是httpclient请求,就需要手动处理,这里使用jdk处理
        pwd= URLEncoder.encode(pwd,StandardCharsets.UTF_8.name());

        String urlPath = "http://localhost:8080/login?userName="+username+"&passWord="+pwd;

        //httpGet
        HttpGet httpGet=new HttpGet(urlPath);
        //解决httpclient被认为不是真人行为(爬虫的应用,防止检测,可不设置)
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
        //防盗链,value必须为该网站的网址(爬虫的应用,可不设置)
        httpGet.addHeader("Referer","https://www.baidu.com/");

        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response=null;
        try {
            //发送请求
            response=closeableHttpClient.execute(httpGet);
            //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
            HttpEntity entity = response.getEntity();
            //对HttpEntity操作的工具类,转成string看下结果
            String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStringResult);
            //确保流关闭
            EntityUtils.consume(entity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (closeableHttpClient!=null){
                closeableHttpClient.close();
            }
            if(response!=null){
                response.close();
            }
        }


    }

获取响应头

在有参请求的基础上,修改了部分代码

            //获取此次请求成功或者失败的状态
            StatusLine statusLine = response.getStatusLine();
            //获取状态码,200、300、400、500
            int statusCode = statusLine.getStatusCode();
            if(HttpStatus.SC_OK==statusCode){
                System.out.println(statusCode+"-请求成功");

                //获取请求头
                Header[] headers = response.getAllHeaders();
                for (Header header:headers){
                    System.out.println("响应头:"+header.getName()+"的值:"+header.getValue());
                }

                //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
                HttpEntity entity = response.getEntity();
                System.out.println("content-type:"+entity.getContentType());

以下是修改后全代码

    /**
     * httpclient发送get请求,测试自己写的接口
     * 有参请求,有些特殊字符,需要处理URLEncoder.encode
     *
     * @throws Exception
     */
    @Test
    void httpClientsController() throws Exception {

        //CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        /*
            HttpClients是一个工具类,等同上面的方法
            可关闭的httpclient客户端,相当于打开的一个浏览器
         */
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        String username="张三";
        //如果字符中包含特殊字符或者空格会报错,需要处理一下
        String pwd="abcd+ |2312";
        //如果是浏览器,会自动帮我们处理,如果是httpclient请求,就需要手动处理,这里使用jdk处理
        pwd= URLEncoder.encode(pwd,StandardCharsets.UTF_8.name());

        String urlPath = "http://localhost:8080/login?userName="+username+"&passWord="+pwd;

        //httpGet
        HttpGet httpGet=new HttpGet(urlPath);
        //解决httpclient被认为不是真人行为(爬虫的应用,防止检测,可不设置)
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
        //防盗链,value必须为该网站的网址(爬虫的应用,可不设置)
        httpGet.addHeader("Referer","https://www.baidu.com/");

        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response=null;
        try {
            //发送请求
            response=closeableHttpClient.execute(httpGet);

            //获取此次请求成功或者失败的状态
            StatusLine statusLine = response.getStatusLine();
            //获取状态码,200、300、400、500
            int statusCode = statusLine.getStatusCode();
            if(HttpStatus.SC_OK==statusCode){
                System.out.println(statusCode+"-请求成功");

                //获取请求头
                Header[] headers = response.getAllHeaders();
                for (Header header:headers){
                    System.out.println("响应头:"+header.getName()+"的值:"+header.getValue());
                }

                //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
                HttpEntity entity = response.getEntity();
                System.out.println("content-type:"+entity.getContentType());

                //对HttpEntity操作的工具类,转成string看下结果
                String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringResult);
                //确保流关闭
                EntityUtils.consume(entity);
            }else{
                System.out.println(statusCode+"-请求异常");
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (closeableHttpClient!=null){
                closeableHttpClient.close();
            }
            if(response!=null){
                response.close();
            }
        }


    }

在这里插入图片描述

图片保存到本地

    /**
     * httpclient获取网络上的图片保存本地
     *
     * @throws Exception
     */
    @Test
    void httpClientsSavePicture() throws Exception {

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        //找一个图片的地址
        String urlPath = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";

        //httpGet
        HttpGet httpGet=new HttpGet(urlPath);

        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response=null;
        try {
            //发送请求
            response=closeableHttpClient.execute(httpGet);

            //获取此次请求成功或者失败的状态
            StatusLine statusLine = response.getStatusLine();

            //获取状态码,200、300、400、500
            int statusCode = statusLine.getStatusCode();
            if(HttpStatus.SC_OK==statusCode){
                System.out.println(statusCode+"-请求成功");

                //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
                HttpEntity entity = response.getEntity();

                //获取响应结果的contentType,都是image/png    image/jpg 等等
                String contentType = entity.getContentType().getValue();
                String suffix=".jpg";
                if(contentType.contains("jpg")||contentType.contains("jpeg")){
                    suffix=".jpg";
                }else if(contentType.contains("png")){
                    suffix=".png";
                }

                //对HttpEntity操作的工具类,转成string看下结果
                //String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);

                //获取的不是文本了了,不能用toString,图片是个二进制文件,使用字节流
                byte[] bytes = EntityUtils.toByteArray(entity);
                //本地路径
                String localAbsPath="D:\\123"+suffix;
                FileOutputStream fileOutputStream=new FileOutputStream(localAbsPath);
                fileOutputStream.write(bytes);
                fileOutputStream.close();



                //确保流关闭
                EntityUtils.consume(entity);
            }else{
                System.out.println(statusCode+"-请求异常");
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (closeableHttpClient!=null){
                closeableHttpClient.close();
            }
            if(response!=null){
                response.close();
            }
        }


    }

在这里插入图片描述

设置访问代理

设置访问代理

        //创建一个代理
        HttpHost proxy=new HttpHost("203.30.191.46",80);

        //对每一个请求进行配置,会覆盖默认的全局配置
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
        httpGet.setConfig(requestConfig);

全代码

    /**
     * httpclient 访问代理
     *
     * @throws Exception
     */
    @Test
    void httpClientsProxy() throws Exception {

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        //找一个图片的地址
        String urlPath = "https://www.baidu.com/";

        //httpGet
        HttpGet httpGet=new HttpGet(urlPath);

        //创建一个代理
        HttpHost proxy=new HttpHost("203.30.191.46",80);

        //对每一个请求进行配置,会覆盖默认的全局配置
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
        httpGet.setConfig(requestConfig);

        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response=null;
        try {
            //发送请求
            response=closeableHttpClient.execute(httpGet);

            //获取此次请求成功或者失败的状态
            StatusLine statusLine = response.getStatusLine();

            //获取状态码,200、300、400、500
            int statusCode = statusLine.getStatusCode();
            if(HttpStatus.SC_OK==statusCode){
                System.out.println(statusCode+"-请求成功");

                //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
                HttpEntity entity = response.getEntity();

                //对HttpEntity操作的工具类,转成string看下结果
                String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringResult);

                //确保流关闭
                EntityUtils.consume(entity);
            }else{
                System.out.println(statusCode+"-请求异常");
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (closeableHttpClient!=null){
                closeableHttpClient.close();
            }
            if(response!=null){
                response.close();
            }
        }


    }

连接超时和读取超时

设置超时代码

     //对每一个请求进行配置,会覆盖默认的全局配置
     RequestConfig requestConfig = RequestConfig.custom()
             //.setProxy(proxy)
             //设置连接超时,单位ms,完成tcp 3次握手的时间上限
             .setConnectTimeout(5000)
             //设置读取超时,单位ms,从请求地址获取响应数据的时间间隔
             .setSocketTimeout(5000)
             //从连接池获取connection的超时时间
             .setConnectionRequestTimeout(5000)
             .build();
     httpGet.setConfig(requestConfig);

全代码

    /**
     * httpclient
     * 连接超时
     * 读取超时
     *
     * @throws Exception
     */
    @Test
    void httpClientsTimeOut() throws Exception {

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        String username = "张三";
        //如果字符中包含特殊字符或者空格会报错,需要处理一下
        String pwd = "abcd+ |2312";
        //如果是浏览器,会自动帮我们处理,如果是httpclient请求,就需要手动处理,这里使用jdk处理
        pwd = URLEncoder.encode(pwd, StandardCharsets.UTF_8.name());

        String urlPath = "http://localhost:8080/login?userName=" + username + "&passWord=" + pwd;

        //httpGet
        HttpGet httpGet = new HttpGet(urlPath);

        //对每一个请求进行配置,会覆盖默认的全局配置
        RequestConfig requestConfig = RequestConfig.custom()
                //.setProxy(proxy)
                //设置连接超时,单位ms,完成tcp 3次握手的时间上限
                .setConnectTimeout(5000)
                //设置读取超时,单位ms,从请求地址获取响应数据的时间间隔
                .setSocketTimeout(5000)
                //从连接池获取connection的超时时间
                .setConnectionRequestTimeout(5000)
                .build();
        httpGet.setConfig(requestConfig);

        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response = null;
        try {
            //发送请求
            response = closeableHttpClient.execute(httpGet);

            //获取此次请求成功或者失败的状态
            StatusLine statusLine = response.getStatusLine();

            //获取状态码,200、300、400、500
            int statusCode = statusLine.getStatusCode();
            if (HttpStatus.SC_OK == statusCode) {
                System.out.println(statusCode + "-请求成功");

                //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
                HttpEntity entity = response.getEntity();

                //对HttpEntity操作的工具类,转成string看下结果
                String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringResult);

                //确保流关闭
                EntityUtils.consume(entity);
            } else {
                System.out.println(statusCode + "-请求异常");
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }


    }

post请求

发送application/x-www-form-urlencoded类型的post请求

主要代码

        //创建HttpPost对象
        HttpPost httpPost=new HttpPost(urlPath);
        //默认就是application/x-www-form-urlencoded,可以不设置
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;chartset=utf-8");

        //给post对象设置参数

        // <input type="text" name="userName">
        // NameValuePair代表input标签的name
        List<NameValuePair> list=new ArrayList<>();
        //第一个参数name的值,第二个参数,input的值
        list.add(new BasicNameValuePair("userName","张三"));
        list.add(new BasicNameValuePair("passWord","13579"));
        //转码
        UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(list,Consts.UTF_8);
        //httpPost请求参数
        httpPost.setEntity(formEntity);

全代码

    /**
     * httpclient   发送application/x-www-form-urlencoded类型的post请求
     * @throws Exception
     */
    @Test
    void httpClientsPost() throws Exception {

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        String urlPath = "http://localhost:8080/testPost";

        //创建HttpPost对象
        HttpPost httpPost=new HttpPost(urlPath);
        //默认就是application/x-www-form-urlencoded,可以不设置
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;chartset=utf-8");

        //给post对象设置参数

        // <input type="text" name="userName">
        // NameValuePair代表input标签的name
        List<NameValuePair> list=new ArrayList<>();
        //第一个参数name的值,第二个参数,input的值
        list.add(new BasicNameValuePair("userName","张三"));
        list.add(new BasicNameValuePair("passWord","13579"));
        //转码
        UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(list,Consts.UTF_8);
        //httpPost请求参数
        httpPost.setEntity(formEntity);


        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response = null;
        try {
            //发送请求
            response = closeableHttpClient.execute(httpPost);

            //获取此次请求成功或者失败的状态
            StatusLine statusLine = response.getStatusLine();

            //获取状态码,200、300、400、500
            int statusCode = statusLine.getStatusCode();
            if (HttpStatus.SC_OK == statusCode) {
                System.out.println(statusCode + "-请求成功");

                //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
                HttpEntity entity = response.getEntity();

                //对HttpEntity操作的工具类,转成string看下结果
                String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringResult);

                //确保流关闭
                EntityUtils.consume(entity);
            } else {
                System.out.println(statusCode + "-请求异常");
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }


    }

发送application/json类型的post请求

主要代码

        //创建HttpPost对象
        HttpPost httpPost=new HttpPost(urlPath);

        //String是一个json字符串
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("userName","张三");
        jsonObject.put("passWord","1231313");


        StringEntity jsonEntity=new StringEntity(jsonObject.toString(),Consts.UTF_8);
        //设置entity内容类型
        jsonEntity.setContentType(new BasicHeader("Content-Type","application/json;utf-8"));
        //设置entity编码
        jsonEntity.setContentEncoding(Consts.UTF_8.name());

        //httpPost请求参数
        httpPost.setEntity(jsonEntity);

全代码

    /**
     * httpclient   发送application/json类型的post请求
     * @throws Exception
     */
    @Test
    void httpClientsPost1() throws Exception {

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        String urlPath = "http://localhost:8080/testJson";

        //创建HttpPost对象
        HttpPost httpPost=new HttpPost(urlPath);

        //String是一个json字符串
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("userName","张三");
        jsonObject.put("passWord","1231313");


        StringEntity jsonEntity=new StringEntity(jsonObject.toString(),Consts.UTF_8);
        //设置entity内容类型
        jsonEntity.setContentType(new BasicHeader("Content-Type","application/json;utf-8"));
        //设置entity编码
        jsonEntity.setContentEncoding(Consts.UTF_8.name());

        //httpPost请求参数
        httpPost.setEntity(jsonEntity);


        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response = null;
        try {
            //发送请求
            response = closeableHttpClient.execute(httpPost);

            //获取此次请求成功或者失败的状态
            StatusLine statusLine = response.getStatusLine();

            //获取状态码,200、300、400、500
            int statusCode = statusLine.getStatusCode();
            if (HttpStatus.SC_OK == statusCode) {
                System.out.println(statusCode + "-请求成功");

                //获取请求头
                Header[] headers = response.getAllHeaders();
                for (Header header:headers){
                    System.out.println("响应头:"+header.getName()+"的值:"+header.getValue());
                }

                //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
                HttpEntity entity = response.getEntity();

                //对HttpEntity操作的工具类,转成string看下结果
                String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringResult);

                //确保流关闭
                EntityUtils.consume(entity);
            } else {
                System.out.println(statusCode + "-请求异常");
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }


    }

httpclient文件请求

主要代码

        //构造文件上传的entity
        MultipartEntityBuilder multipartEntityBuilder=MultipartEntityBuilder.create();
        //设置编码
        multipartEntityBuilder.setCharset(Consts.UTF_8);
        //设置content-type
        multipartEntityBuilder.setContentType(ContentType.create("multipart/form-data", Consts.UTF_8));
        //设置浏览器模式
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        //构建一个contentbody对象
        FileBody fileBody=new FileBody(new File("D:\\day42.log"));
        //addTextBody中文参数乱码,使用stringbody
        StringBody stringBody=new StringBody("张三",ContentType.create("text/plan", Consts.UTF_8));

        /**
         * 文件:<input type="file" name="fileName">
         *     addPart("fileName", fileBody)
         *     addBinaryBody("fileName", new File("D:\\11.jpg"))
         *
         *  文本:       用户名:<input type="text" name="userName">
         *                      addTextBody("userName", "张三")
         *                      中文乱码,使用StringBody处理
         *
         *             密码:<input type="password" name="passWord">
         *                    addTextBody("passWord", "154sadas")
         *
         */
        HttpEntity httpEntity = multipartEntityBuilder.addPart("fileName", fileBody)
                //通过file,byt[],inputstream上传文件
                .addBinaryBody("fileName", new File("D:\\11.jpg"))
                .addPart("userName",stringBody)
                .addTextBody("passWord", "154sadas").build();



        //httpPost请求参数
        httpPost.setEntity(httpEntity);

全部代码

    /**
     * httpclient   发送multipart/form-data类型的post请求
     * @throws Exception
     */
    @Test
    void testMultipartFile() throws Exception {

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        String urlPath = "http://localhost:8080/testMultipartFile";

        //创建HttpPost对象
        HttpPost httpPost=new HttpPost(urlPath);

        //构造文件上传的entity
        MultipartEntityBuilder multipartEntityBuilder=MultipartEntityBuilder.create();
        //设置编码
        multipartEntityBuilder.setCharset(Consts.UTF_8);
        //设置content-type
        multipartEntityBuilder.setContentType(ContentType.create("multipart/form-data", Consts.UTF_8));
        //设置浏览器模式
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        //构建一个contentbody对象
        FileBody fileBody=new FileBody(new File("D:\\day42.log"));
        //addTextBody中文参数乱码,使用stringbody
        StringBody stringBody=new StringBody("张三",ContentType.create("text/plan", Consts.UTF_8));

        /**
         * 文件:<input type="file" name="fileName">
         *     addPart("fileName", fileBody)
         *     addBinaryBody("fileName", new File("D:\\11.jpg"))
         *
         *  文本:       用户名:<input type="text" name="userName">
         *                      addTextBody("userName", "张三")
         *                      中文乱码,使用StringBody处理
         *
         *             密码:<input type="password" name="passWord">
         *                    addTextBody("passWord", "154sadas")
         *
         */
        HttpEntity httpEntity = multipartEntityBuilder.addPart("fileName", fileBody)
                //通过file,byt[],inputstream上传文件
                .addBinaryBody("fileName", new File("D:\\11.jpg"))
                .addPart("userName",stringBody)
                .addTextBody("passWord", "154sadas").build();



        //httpPost请求参数
        httpPost.setEntity(httpEntity);


        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response = null;
        try {
            //发送请求
            response = closeableHttpClient.execute(httpPost);

            //获取此次请求成功或者失败的状态
            StatusLine statusLine = response.getStatusLine();

            //获取状态码,200、300、400、500
            int statusCode = statusLine.getStatusCode();
            if (HttpStatus.SC_OK == statusCode) {
                System.out.println(statusCode + "-请求成功");

                //获取请求头
                Header[] headers = response.getAllHeaders();
                for (Header header:headers){
                    System.out.println("响应头:"+header.getName()+"的值:"+header.getValue());
                }

                //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
                HttpEntity entity = response.getEntity();

                //对HttpEntity操作的工具类,转成string看下结果
                String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringResult);

                //确保流关闭
                EntityUtils.consume(entity);
            } else {
                System.out.println(statusCode + "-请求异常");
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }


    }

https连接

访问安全的https连接,是正常的

如果访问非安全的https,就会报错,需要绕过https

    /**
     * 测试https:配置httpclient绕过https安全认证
     *  否则报错 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed
     * @throws Exception
     */
    @Test
    void testHttps() throws Exception {

        //
        Registry<ConnectionSocketFactory> build = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", trustHttpsCertificates()).build();

        //创建ClientConnectionManager
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(build);
        //定制CloseableHttpClient对象
        HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager);


        //配置好HttpClient之后,通过build获取CloseableHttpClient对象
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

        String urlPath = "https://localhost:8081/login";
        //httpGet
        HttpGet httpGet = new HttpGet(urlPath);

        //可关闭的响应:DecopressingEntity
        CloseableHttpResponse response = null;
        try {
            //发送请求
            response = closeableHttpClient.execute(httpGet);
            //获取响应结果:HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
            HttpEntity entity = response.getEntity();
            //对HttpEntity操作的工具类,转成string看下结果
            String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStringResult);
            //确保流关闭
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }


    }

    //创建支持安全协议的连接工厂
    private ConnectionSocketFactory trustHttpsCertificates() throws Exception {

        SSLContextBuilder sslContextBuilder=new SSLContextBuilder();
        //加载信任的证书
        sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
            //判断是否信任url,全都信任,返回true
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext=sslContextBuilder.build();

        SSLConnectionSocketFactory  sslConnectionSocketFactory=new SSLConnectionSocketFactory(sslContext,new String[]{"SSLv2Hello","SSLv3","TLSv1","TLSv1.1","TLSv1.2"},null, NoopHostnameVerifier.INSTANCE);
        return sslConnectionSocketFactory;

    }

先准备自制证书,自制证书是非安全的https,把项目变成https再测试访问:https://blog.csdn.net/a3562323/article/details/124490968?spm=1001.2014.3001.5501

使用httpclient连接池

创建连接池

    private static final HttpClientBuilder httpClientBuilder= HttpClients.custom();
    private static JSONObject jsonObject=new JSONObject();
    static {
    //    绕过不安全的https请求的证书验证
        Registry<ConnectionSocketFactory> build = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", trustHttpsCertificates()).build();

        //创建连接池
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(build);
        //连接池最大连接
        poolingHttpClientConnectionManager.setMaxTotal(50);
        /**
         * 每个路由默认多少个连接
         *      https://www.asdsad.com/login
         *      https://www.asdsad.com/mian
         *      都是一个路由
         * https://1gqsad/login
         *      一个域名又是一个新的路由
         */
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(50);

        httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);

    //    设置请求默认配置
        RequestConfig requestConfig=RequestConfig.custom()
                //设置连接超时,单位ms,完成tcp 3次握手的时间上限
                .setConnectTimeout(5000)
                //设置读取超时,单位ms,从请求地址获取响应数据的时间间隔
                .setSocketTimeout(3000)
                //从连接池获取connection的超时时间
                .setConnectionRequestTimeout(3000)
                .build();
        httpClientBuilder.setDefaultRequestConfig(requestConfig);

    //    设置默认的header
/*        List<Header> defaultHeaders=new ArrayList<>();
        BasicHeader userAgentHeader=new BasicHeader("User-Agent","Mozilla/5.0");
        defaultHeaders.add(userAgentHeader);
        httpClientBuilder.setDefaultHeaders(defaultHeaders);*/
    }

每次获取CloseableHttpClient对象时,直接使用连接池创建的对象httpClientBuilder.build()

CloseableHttpClient closeableHttpClient=httpClientBuilder.build();

客户端推送json到服务端,数据结构发生了改变,本来是List<User >的结构,接收以后,变成了List<LinkedHashMap>

之前使用过ObjectMapper来转字符串,现在可以通过ObjectMapper再把List< LinkedHashMap >转成List< Object >
ObjectMapper使用的包:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
alibaba也有TypeReference,TypeReference报错的话,确认一下包是否正确

ObjectMapper objectMapper=new ObjectMapper()
List<User> list = objectMapper.convertValue(lists, new TypeReference<List<User>>(){});

太多代码,贴不全,需要全代码的私聊

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值