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_第1张图片

图片保存到本地

    /**
     * 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();
            }
        }


    }

httpClient_第2张图片

设置访问代理

设置访问代理

        //创建一个代理
        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对象设置参数

        // 
        // 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对象设置参数

        // 
        // 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));

        /**
         * 文件:
         *     addPart("fileName", fileBody)
         *     addBinaryBody("fileName", new File("D:\\11.jpg"))
         *
         *  文本:       用户名:
         *                      addTextBody("userName", "张三")
         *                      中文乱码,使用StringBody处理
         *
         *             密码:
         *                    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));

        /**
         * 文件:
         *     addPart("fileName", fileBody)
         *     addBinaryBody("fileName", new File("D:\\11.jpg"))
         *
         *  文本:       用户名:
         *                      addTextBody("userName", "张三")
         *                      中文乱码,使用StringBody处理
         *
         *             密码:
         *                    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();
            }
        }


    }

你可能感兴趣的:(httpclient)