HttpClient发送get/post请求

摘要:
版本>4.5<org.apache.httpcomponents<版本>&书信电报;https;rsv_ idx=1&tn=百度&wd=helloworld&rsv_ enter=1&

参考博客:https://www.cnblogs.com/LuckyBao/p/6096145.html

1.需要的maven依赖:

<!--httpClient需要的依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <!--//httpclient缓存-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient-cache</artifactId>
            <version>4.5</version>
        </dependency>
        <!--//http的mime类型都在这里面-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.2</version>
        </dependency>

2.发送get请求

//使用httpClient发送get请求
    public void sentGetMethod(){
        //1.先创建httpClient对象,使用默认的方式即可
        CloseableHttpClient httpClient= HttpClients.createDefault();

        //2.设置url并且创建某种请求方式实例
        //比如:(在百度上搜索helloworld出现的路径)url:https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0
        // &rsv_idx=1&tn=baidu&wd=helloworld&rsv_pq=c6735cf70000fe15
        // &rsv_t=7e25dm7uzHpmOwrFNF33FXbom45Px0Bs0F8PP3Bcm8RMOysmKlfA%2FuqKoU4&rqlang=cn
        // &rsv_enter=1&rsv_sug3=9&rsv_sug1=5&rsv_sug7=101
        //url的构建也可以使用字符串拼接的方式
        try {
            URI url=new URIBuilder()
                    .setScheme("https")//设置协议
                    .setHost("www.baidu.com")
                    .setPath("/s")
                    .setParameter("ie","utf-8")
                    .setParameter("rsv_idx","1")
                    .setParameter("tn","baidu")
                    .setParameter("wd","helloworld")
                    .setParameter("rsv_pq","c6735cf70000fe15")
                    .setParameter("rsv_t","7e25dm7uzHpmOwrFNF33FXbom45Px0Bs0F8PP3Bcm8RMOysmKlfA%2FuqKoU4")
                    .setParameter("rqlang","cn")
                    .setParameter("rsv_enter","1")
                    .setParameter("rsv_sug3","9")
                    .setParameter("rsv_sug1","5")
                    .setParameter("rsv_sug7","101")
                    .build();
            System.out.println(url);
            HttpGet httpGet=new HttpGet(url);
            InputStream inputStream=null;
            CloseableHttpResponse httpResponse=null;
            try {
                //3.执行httpClient
                httpResponse=httpClient.execute(httpGet);
                //可以输出请求的结果
                System.out.println(httpResponse.getStatusLine().getStatusCode());
                //4.获取相应的结果
                //4.1使用EntityUtils.toString()方式  --不推荐
                //2种方式只能2选一存在,会互相冲突
                HttpEntity entity=httpResponse.getEntity();  //获取响应的实体
//                if (entity!=null){
//                    System.out.println(EntityUtils.toString(entity,"utf-8"));
//                }else {
//                    //如果entity为空,那么直接消化掉即可
//                    EntityUtils.consume(entity);
//                }
                System.out.println("------------------------我是美丽的分割线--------------------");
                //4.2使用InputStream方式   --推建
                inputStream=entity.getContent();
                //转换成字符流
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                String line="";
                while ((line=bufferedReader.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //关闭InputStream和response
                if (inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (httpResponse!=null){
                    try {
                        httpResponse.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ;
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }

 3.httpClient发送post请求(携带json数据)

//发送post请求 携带json数据的
    public void sendPostMethod(String url){
        //1.创建httpClient
        CloseableHttpClient httpClient=HttpClients.createDefault();
        //2.创建post请求方式实例
        HttpPost httpPost=new HttpPost(url);

        //2.1设置请求头 发送的是json数据格式
        httpPost.setHeader("Content-type", "application/json;charset=utf-8");
        httpPost.setHeader("Connection", "Close");

        //3.设置参数---设置消息实体 也就是携带的数据
        /*
        * 比如传递:
        * {
                "username": "aries",
                "password": "666666"
            }
         */
        String jsonStr=" {"username":"aries","password":"666666"}";
        StringEntity entity = new StringEntity(jsonStr.toString(), Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");  //设置编码格式
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        //把请求消息实体塞进去
        httpPost.setEntity(entity);

        //4.执行http的post请求
        CloseableHttpResponse httpResponse=null;
        InputStream inputStream=null;
        try {
             httpResponse=httpClient.execute(httpPost);
             //5.对返回的数据进行处理
            //5.1判断是否成功
            System.out.println(httpResponse.getStatusLine().getStatusCode());

            //5.2对数据进行处理
            HttpEntity httpEntity=httpResponse.getEntity();
            inputStream=httpEntity.getContent(); //获取content实体内容
            //封装成字符流来输出
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
            String line="";
            while ((line=bufferedReader.readLine())!=null){
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //6.关闭inputStream和httpResponse
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse!=null){
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 4.httpClient发送post请求/携带x-www-form-urlencoded数据格式

//发送post请求 携带非json数据
    public  void sendPostMethod1(String url) throws Exception {
        // 1、创建一个httpClient客户端对象
        CloseableHttpClient httpClient=HttpClients.createDefault();
        // 2、创建一个HttpPost请求
        HttpPost httpPost = new HttpPost(url);
        //设置请求头
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); //设置传输的数据格式

        //携带普通的参数params的方式
        List<NameValuePair> params=new ArrayList<>();
        params.add(new BasicNameValuePair("username", "kylin"));
        params.add(new BasicNameValuePair("password", "123456"));

        String str=EntityUtils.toString(new UrlEncodedFormEntity(params,Consts.UTF_8));
        //这里就是:username=kylin&password=123456
        System.out.println(str);

        //放参数进post请求里面  从名字可以知道 这个类是专门处理x-www-form-urlencoded 添加参数的
        httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

        // 7、执行post请求操作,并拿到结果
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

        // 获取结果实体
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            //进行输出操作 这里就简单的使用EntityUtils工具类的toString()方法
            System.out.println(EntityUtils.toString(entity,"UTF-8"));
        }
        else EntityUtils.consume(entity);
        //最后释放资源之类的
    }

总结:

  1.创建httpClient对象创建默认的对象就够使用了

  2.创建某种请求方法的实例

    例如有:get方式---- HttpGet
        post方式-----HttpPost
        put方式------HttpPut
        delete方式 ------HttpDelete
  3.如果有参数的话就设置参数  

    get请求:
      方式1:使用URI类的方法来创建
      方式2:直接使用字符串拼接那种

    post请求:

      使用setEntity()方式来携带不同的数据类型(需要设置)
  4.发送请求
    执行httpClient.execute() --返回CloseableHttpResponse对象
  5.获取请求的结果
    获取HttpEntity的实体之后,对http文档的查看
      方式一:EntityUtils.toString(entity,"utf-8") 不推荐
      方式二:使用InputStream类
  6.关闭连接释放资源
    先关闭inputStream
    再关闭response

免责声明:文章转载自《HttpClient发送get/post请求》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇UNIX网络编程 卷2 源代码使用liunx安装mysql(mariadb)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

9款让你眼前一亮的HTML5/CSS3示例及源码

1、HTML5 3D点阵列波浪翻滚动画 今天我们要再分享一款基于HTML5 3D的点阵列波浪翻滚动画特效,同样是非常的壮观。 在线演示 源码下载 2、HTML5小球弹跳动画 很不错的3D小球 今天我要向大家分享一款很逼真的HTML5动画特效,它是3个色彩各异的弹跳小球,每一个小球在弹跳的时候都会有变化的小球投影,让整个动画更加逼真,而且具有3D的视觉效果...

Zabbix监控系统配置

              1、Zabbix是一个基于WEB界面的提供分布式系统监控的企业级的开源解决方案 Zabbix能监视各种网络参数,保证服务器系统的安全稳定的运行,并提供灵活的通知机制以让SA快速定位并解决存在的各种问题 。有点有如下: q 支持自动发现服务器和网络设备; q 支持底层自动发现; q 分布式的监控体系和集中式的WEB管理; q 支持...

APM系统SkyWalking介绍

  公司最近在构建服务化平台,需要上线APM系统,本篇文章简单的介绍SkyWalking APM APM全称Application Performance Management应用性能管理,目的是通过各种探针采集数据,收集关键指标,同时搭配数据呈现以实现对应用程序性能管理和故障管理的系统化解决方案 Zabbix、Premetheus、open-falco...

hive 存储,解析,处理json数据

 hive 处理json数据总体来说有两个方向的路走 1、将json以字符串的方式整个入Hive表,然后通过使用UDF函数解析已经导入到hive中的数据,比如使用LATERAL VIEW json_tuple的方法,获取所需要的列名。 2、在导入之前将json拆成各个字段,导入Hive表的数据是已经解析过得。这将需要使用第三方的SerDe。 测试数据为新浪...

USB转UART相关芯片

CP210X 系类官网地址 CP2102参考外围电路 CP2102 Pin Definitions Name Pin # Type Description  说明 VDD 6 Power In Power Out 3.0–3.6 V Power Supply Voltage Input. 3.3 V Voltage Regulator...

Python爬取中文页面的时候出现的乱码问题

一、读取返回的页面数据 在浏览器打开的时候查看源代码,如果在头部信息中指定了UTF-8 那么再python代码中读取页面信息的时候,就需要指定读取的编码方式: response.read().decode('utf-8') 二、把中文数据写入到文件的时候 python默认的是按照ACSII的编码往外写,所以中文数据往外写肯定会出现乱码 那么再往外写入文件的...