HttpClient基本使用

原java发送请求

public static void main(String[] args) throws IOException {

    // 1-构造一个url
    URL url = new URL("http://www.baidu.com");
//        URL url = new URL("http://localhost:8080/hello");

    // 2-构造一个连接 设置相关配置属性
    HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
    urlconn.setRequestMethod("GET"); //设置请求方式
    urlconn.setConnectTimeout(5000);
    urlconn.setReadTimeout(5000);
    urlconn.setUseCaches(false);

    // 3-设置请求头(请求属性) 这里为模拟浏览器
//        urlconn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36");

    // 4-获取连接
    urlconn.connect();

    // 5-获取连接的流对象 读取源码数据
    InputStream inputStream = urlconn.getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
    BufferedReader buff = new BufferedReader(inputStreamReader);

    String line = null;
    while ((line = buff.readLine()) != null){
        System.out.println(line);
    }
    inputStream.close();
    inputStreamReader.close();
    buff.close();
}

httpclient发送请求

public static void main(String[] args) throws IOException, ParseException {

    //获取一个客户端
    CloseableHttpClient aDefault = HttpClients.createDefault();

    //定义请求配置
    RequestConfig requestConfig = RequestConfig.custom()
            //连接超时时间
            .setConnectTimeout(30, TimeUnit.SECONDS)
            //连接请求超时时间
            .setConnectionRequestTimeout(10,TimeUnit.SECONDS)
            //响应超时时间
            .setResponseTimeout(10,TimeUnit.SECONDS)
            .build();

    /**
     * Get请求
     */
//        HttpGet httpGet = new HttpGet("http://localhost:8080/hello");
//        httpGet.setConfig(requestConfig); //设置请求配置

//        //执行请求
//        CloseableHttpResponse response = aDefault.execute(httpGet);
          
          // 获取响应码
//        System.out.println("响应码:"+response.getCode());

          // 获取响应实体
//        HttpEntity entity = response.getEntity();
//        System.out.println("实体"+ entity);

          // 通过工具类可以获取响应体内容
//        String s = EntityUtils.toString(entity);
//        System.out.println(s);

------------------执行结果
响应码:200
实体Wrapper [[Content-Type: text/plain;charset=UTF-8,Content-Encoding: null,Content-Length: 8,Chunked: false]]
hello!!!


    /**
     * Post请求
     */
//        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getp");
    HttpPost httpPost = new HttpPost("http://localhost:8080/hello");
    httpPost.setConfig(requestConfig); //设置请求配置
    httpPost.setHeader("Content-Type","application/json");

    //执行请求
    CloseableHttpResponse response = aDefault.execute(httpPost);

    // 获取响应码
    System.out.println("响应码:"+response.getCode());

    // 获取响应实体
    HttpEntity entity = response.getEntity();
    System.out.println("实体"+ entity);

    // 通过工具类可以获取响应体内容
    String s = EntityUtils.toString(entity);
    System.out.println(s);

------------------执行结果
响应码:200
实体Wrapper [[Content-Type: text/plain;charset=UTF-8,Content-Encoding: null,Content-Length: 8,Chunked: false]]
hello!!!

}

httpclient

springboot编写接口

  • 实体类
public class Person implements Serializable {

    private String name;
    private String sex;

    public Person() {
    }

    public Person(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}
  • 接口
@Controller
public class TestController {

    // get不带参
    @RequestMapping(value = "/test/getpGet",method = RequestMethod.GET)
    @ResponseBody
    public String getPersonGet1(){
        return "hello!!!--get";
    }

    // get带参
    @RequestMapping(value = "/test/getpGetParam",method = RequestMethod.GET)
    @ResponseBody
    public Person getPersonGet2(String name,String sex){
        Person p = new Person(name,sex);
        System.out.println(p);
        return p;
    }

    // post不带参
    @RequestMapping(value = "/test/getpPost",method = RequestMethod.POST)
    @ResponseBody
    public String getPersonPost1(){
        return "hello!!!--post";
    }

    // post带参--引用类型参
    @RequestMapping(value = "/test/getpPostParam",method = RequestMethod.POST)
    @ResponseBody
    public Person getPersonPost2(Person person){
        System.out.println(person);
        return person;
    }

    // post带参--json类型参
    @RequestMapping(value = "/test/getpPostParamJson",method = RequestMethod.POST)
    @ResponseBody
    public Person getPersonPost3(@RequestBody Person person){
        System.out.println(person);
        return person;
    }
}

get请求

public class HttpclientGet {

    public static void main(String[] args) throws Exception {
        //创建httpget对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建请求对象 设置url
        HttpGet httpGet = new HttpGet("http://localhost:8080/test/getpGet");

        CloseableHttpResponse response = null;
        // 发起请求,获取response
        response = httpClient.execute(httpGet);
        // 解析
        if (response.getCode() == 200){
            String content  = EntityUtils.toString(response.getEntity(),"utf8");
            System.out.println(content);
        }
        response.close();
        httpClient.close();
    }
}

----------结果
hello!!!--get

get请求传参

public class HttpclientGetParam {

    public static void main(String[] args) throws Exception {
        // 创建httpget对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // ---创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/test/getpGetParam");
//        uriBuilder.setParameter("name","xiaoai");
//        uriBuilder.setParameter("sex","nan");

        // ---多参数可用链式编程
        uriBuilder.setParameter("name","xiaoai")
                .setParameter("sex","nan");

        // ---创建get请求
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        CloseableHttpResponse response = null;
        // 发起请求,获取response
        response = httpClient.execute(httpGet);
        // 解析
        if (response.getCode() == 200){
            String content  = EntityUtils.toString(response.getEntity(),"utf8");
            System.out.println(content);
        }
        response.close();
        httpClient.close();
    }
}

----------结果
{"name":"xiaoai","sex":"nan"}

post请求

public class HttpclientPost {

    public static void main(String[] args) throws Exception {
        // 创建httpget对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建请求对象 设置url
        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getpPost");

        CloseableHttpResponse response = null;
        // 发起请求,获取response
        response = httpClient.execute(httpPost);
        // 解析
        if (response.getCode() == 200){
            String content  = EntityUtils.toString(response.getEntity(),"utf8");
            System.out.println(content);
        }
        response.close();
        httpClient.close();
    }
}

----------结果
hello!!!--post

post请求传参

1-表单传参

public class HttpclientPostParamForm {

    public static void main(String[] args) throws Exception {
        // 创建httpget对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建请求对象 设置url
        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getpPostParam");

        // ---list集合,封装表单中参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("name","xiaoai"));
        params.add(new BasicNameValuePair("sex","nan"));
        // ---创建表单Entity对象
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, Charset.defaultCharset());
        // ---设置表单的Entity对象到post请求
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        // 发起请求,获取response
        response = httpClient.execute(httpPost);
        // 解析
        System.out.println(response.getCode()+"=========");
        if (response.getCode() == 200){
            String content  = EntityUtils.toString(response.getEntity(),"utf8");
            System.out.println(content);
        }
        response.close();
        httpClient.close();
    }
}

----------结果
{"name":"xiaoai","sex":"nan"}

2-json格式传参

public class HttpclientPostParamJson {

    public static void main(String[] args) throws IOException, ParseException {
        // 创建httpget对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建请求对象 设置url
        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getpPostParamJson");

        // ---请求头设置传参格式
        httpPost.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
        // ---创建传递的json字符参数
        JSONObject param = new JSONObject();
        param.put("name","xiaoai");
        param.put("sex","nan");
        StringEntity StringEntity = new StringEntity(param.toString());
        // ---设置表单的Entity对象到post请求
        httpPost.setEntity(StringEntity);

        CloseableHttpResponse response = null;
        // 发起请求,获取response
        response = httpClient.execute(httpPost);
        // 解析
        if (response.getCode() == 200){
            String content  = EntityUtils.toString(response.getEntity(),"utf8");
            System.out.println(content);
        }
        response.close();
        httpClient.close();
    }
}

----------结果
{"name":"xiaoai","sex":"nan"}

连接池和请求配置java

public class HttpClientPoolT {

    public static void main(String[] args) throws Exception {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

        // 设置连接池配置,
        // 最大连接数,即连接池中客户端数量
        cm.setMaxTotal(100);
        // 每个主机最大连接数 ,即每个主机最多连接的客户端数量
        cm.setDefaultMaxPerRoute(10);

        // 使用连接池发送请求,通过debug可查看每次生成的httpClient都不同
        doGet(cm);
        doPost(cm);

        // ----带请求配置
        //设置请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                //连接超时时间
                .setConnectTimeout(30, TimeUnit.SECONDS)
                //连接请求超时时间
                .setConnectionRequestTimeout(10,TimeUnit.SECONDS)
                //响应超时时间
                .setResponseTimeout(10,TimeUnit.SECONDS)
                .build();

        doGet(cm,requestConfig);
        doPost(cm,requestConfig);

    }

    
    //===============================================================
    private static void doGet(PoolingHttpClientConnectionManager cm) throws Exception {

        // 从连接池管理器中获取客户端
        HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(cm);
        CloseableHttpClient httpClient = httpClientBuilder.build();

        HttpGet httpGet = new HttpGet("http://localhost:8080/test/getpGet");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getCode() == 200){
            String content = EntityUtils.toString(response.getEntity(), Charset.defaultCharset());
            System.out.println(content);
        }
        //关闭响应
        response.close();
        //使用连接池,不需要自己关闭httpClient连接
//        httpClient.close();
    }

    private static void doPost(PoolingHttpClientConnectionManager cm) throws Exception {
        // 从连接池管理器中获取客户端
        HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(cm);
        CloseableHttpClient httpClient = httpClientBuilder.build();

        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getpPost");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getCode() == 200){
            String content = EntityUtils.toString(response.getEntity(), Charset.defaultCharset());
            System.out.println(content);
        }
        //关闭响应
        response.close();
        //使用连接池,不需要自己关闭httpClient连接
//        httpClient.close();
    }


    
    //===============================================================
    private static void doGet(PoolingHttpClientConnectionManager cm, RequestConfig requestConfig) throws Exception {
        // 从连接池管理器中获取客户端
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpGet httpGet = new HttpGet("http://localhost:8080/test/getpGet");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        if (response.getCode() == 200){
            String content = EntityUtils.toString(response.getEntity(), Charset.defaultCharset());
            System.out.println(content);
        }
        //关闭响应
        response.close();
        //使用连接池,不需要自己关闭httpClient连接
//        httpClient.close();

    }

    private static void doPost(PoolingHttpClientConnectionManager cm, RequestConfig requestConfig)throws Exception {

        // 从连接池管理器中获取客户端
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();

        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getpPost");
        httpPost.setConfig(requestConfig); //连接池不设置请求配置,在请求这里也可以设置
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getCode() == 200){
            String content = EntityUtils.toString(response.getEntity(), Charset.defaultCharset());
            System.out.println(content);
        }
        //关闭响应
        response.close();
        //使用连接池,不需要自己关闭httpClient连接
//        httpClient.close();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值