IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> HttpClient入门教程 -> 正文阅读

[网络协议]HttpClient入门教程

public class HttpClientTest {


    /**
     * 使用HttpClient 发送Get 请求
     */
    @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=http%3A%2F%2Fdpic.tiankong.com%2Fii%2Fw0%2FQJ6643282250.jpg%3Fx-oss-process%3Dstyle%2Fshows&refer=http%3A%2F%2Fdpic.tiankong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640341198&t=338b118e4678ad3e5d3be5d6e9d3f061";
        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<NameValuePair> 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();
                }
            }
        }
    }
    }
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-11-26 09:12:21  更:2021-11-26 09:12:51 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 7:52:23-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码