栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

HttpClient入门教程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

HttpClient入门教程

public class HttpClientTest {


    
    @Test
    public void testGet1() {
        //可关闭的httpClient 客户端,相当于打开的浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String url = "https://www.baidu.com";
        //构造HttpClient 请求对象
        HttpGet httpGet = new HttpGet(url);
        //解决httpClient 认为不是真人行为
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36");
        //防盗链
        httpGet.addHeader("Referer", "https://www.baidu.com/");
        //响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            //获取响应结果
            HttpEntity entity = response.getEntity();
            //HttpClient 工具
            String toStringRusult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStringRusult);
            //确保流关闭
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void testGet2() throws UnsupportedEncodingException {
        //可关闭的httpClient 客户端,相当于打开的浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String name = "Dave+123|abdc  000";
        int age = 15;
        name = URLEncoder.encode(name, StandardCharsets.UTF_8.name());
        String url = "http://192.168.10.115:9999/test/testController1?age=" + age + "&name=" + name;
        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            //请求状态
            StatusLine statusLine = response.getStatusLine();
            System.out.println("请求状态" + statusLine);
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                System.out.println("请求成功");
                Header[] allHeaders = response.getAllHeaders();
                for (Header header : allHeaders) {
                    System.out.println("响应头" + header.getName() + ";响应内容:" + header.getValue());
                }
                //获取响应结果
                HttpEntity entity = response.getEntity();
                System.out.println("ContentType:" + entity.getContentType());
                //HttpClient 工具
                String toStringRusult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringRusult);
                //确保流关闭
                EntityUtils.consume(entity);
            } else {
                System.out.println("响应失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //获取网络图片下载
    @Test
    public void testGet3() throws Exception {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String url = "https://gimg2.baidu.com/image_search/src=https://www.mshxw.com/skin/sinaskin/image/nopic.gif";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            //获取响应结果
            HttpEntity entity = response.getEntity();
            String contentType = entity.getContentType().getValue();
            String suffix = null;
            if (contentType.contains("jpg") || contentType.contains("jpeg")) {
                suffix = ".jpg";
            } else if (contentType.contains("bmp") || contentType.contains("bitmap")) {
                suffix = ".bmp";
            } else if (contentType.contains("png")) {
                suffix = ".png";
            } else if (contentType.contains("gif")) {
                suffix = ".gif";
            }
            //获取文件字节流
            byte[] bytes = EntityUtils.toByteArray(entity);
            String localAbsPath = "test_photo/abc" + suffix;
            FileOutputStream fos = new FileOutputStream(localAbsPath);
            fos.write(bytes);
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //设置访问代理
    @Test
    public void testGet4() {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String url = "https://www.baidu.com";
        HttpGet httpGet = new HttpGet(url);
        //创建一个代理
        String ip = "115.223.7.34";
        int port = 80;
        HttpHost proxy = new HttpHost(ip, port);
        //针对每个请求特殊的定制
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(proxy)
                //连接超时,tcp 三次握手的时间上限
                .setConnectTimeout(5000)
                //读取时间超时ms,表示从请求的网址处获得响应数据的时间间隔
                .setSocketTimeout(3000)
                .build();
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStringResult);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //测试post 请求
    @Test
    public void testPost1() throws UnsupportedEncodingException {
        //可关闭的httpClient 客户端,相当于打开的浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String url = "http://192.168.10.115:9999/test/testController2";
        HttpPost httpPost = new HttpPost(url);
        //给Post 对象设置参数
        // NamevaluePair input 标签里面输入的值
        List list = new ArrayList<>();
        list.add(new BasicNamevaluePair("name","张三"));
        list.add(new BasicNamevaluePair("age","100"));
        //把参数集合设置给FormEntity
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,Consts.UTF_8);
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpPost);
            //请求状态
            StatusLine statusLine = response.getStatusLine();
            System.out.println("请求状态" + statusLine);
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                System.out.println("请求成功");
                Header[] allHeaders = response.getAllHeaders();
                for (Header header : allHeaders) {
                    System.out.println("响应头" + header.getName() + ";响应内容:" + header.getValue());
                }
                //获取响应结果
                HttpEntity entity = response.getEntity();
                System.out.println("ContentType:" + entity.getContentType());
                //HttpClient 工具
                String toStringRusult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringRusult);
                //确保流关闭
                EntityUtils.consume(entity);
            } else {
                System.out.println("响应失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //发送 application/json 类型的 post 请求
    @Test
    public void testPost2() throws UnsupportedEncodingException {
        //可关闭的httpClient 客户端,相当于打开的浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String url = "http://192.168.10.115:9999/test/testController2";
        HttpPost httpPost = new HttpPost(url);
        //设置实体
        JSonObject jsonObject = new JSonObject();
        jsonObject.put("name","小可爱");
        jsonObject.put("age",31);
        StringEntity jsonEntity = new StringEntity(String.valueOf(jsonObject),Consts.UTF_8);
        //给entity 设置内容类型
        jsonEntity.setContentType(new BasicHeader("Content-Type","application/json;charset=utf-8"));
        //设置编码
        jsonEntity.setContentEncoding(Consts.UTF_8.name());
        httpPost.setEntity(jsonEntity);
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpPost);
            //请求状态
            StatusLine statusLine = response.getStatusLine();
            System.out.println("请求状态" + statusLine);
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                System.out.println("请求成功");
                Header[] allHeaders = response.getAllHeaders();
                for (Header header : allHeaders) {
                    System.out.println("响应头" + header.getName() + ";响应内容:" + header.getValue());
                }
                //获取响应结果
                HttpEntity entity = response.getEntity();
                System.out.println("ContentType:" + entity.getContentType());
                //HttpClient 工具
                String toStringRusult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringRusult);
                //确保流关闭
                EntityUtils.consume(entity);
            } else {
                System.out.println("响应失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/602752.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号