httpclient5.0版本使用

20 篇文章 0 订阅

代码环境

纯普通的java项目,没有什么框架

官方教程

HttpClient Quick Start

下载依赖

在这里插入图片描述

Q:为什么还要下载slf4j的依赖?不是httpclient就行了吗
A :不行的,不装的话就会报错在HttpClients.createDefault 这一行代码时候出现了NoClassDefFoundError的错误,详情见HttpClients.createDefault NoClassDefFoundError
在这里插入图片描述

代码

package httpclient;

import com.google.gson.Gson;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.http.NameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {
    @org.junit.Test
    public void getUrlTest() {
        CloseableHttpClient httpclient=HttpClients.createDefault();
        HttpGet httpGet= new HttpGet("https://api.github.com/search/repositories?q=v&sort=stars");
        try {
            // The underlying HTTP connection is still held by the response object
            // to allow the response content to be streamed directly from the network socket.
            // In order to ensure correct deallocation of system resources
            // the user MUST call CloseableHttpResponse#close() from a finally clause.
            // Please note that if response content is not fully consumed the underlying
            // connection cannot be safely re-used and will be shut down and discarded
            // by the connection manager.
            //为了能让返回的内容从网络Socket直接获得,http连接会被返回的对象(response1)所控制。
            //为了确保系统资源,必须在finally里面调用CloseableHttpResponse对象的close()方法
            //请注意如果返回的内容没有被完全消费掉,这个连接再次使用时候就会不安全并且会被自动关闭。
            try {
                CloseableHttpResponse response1 = httpclient.execute(httpGet);
                System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
                HttpEntity entity1 = response1.getEntity();
                // do something useful with the response body
                //拿返回值做些事情
                String strResult = EntityUtils.toString(response1.getEntity());
                System.out.println(strResult);
                // and ensure it is fully consumed
                //确保被消费掉
                EntityUtils.consume(entity1);//消费
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();//关闭
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    @org.junit.Test
    public void postTest() throws IOException {
        CloseableHttpClient httpclient=HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://httpbin.org/post");
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);
        try {
            System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            String strResult = EntityUtils.toString(response2.getEntity());
            System.out.println(strResult);
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();//关闭
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值