HttpClient入门学习

转载自https://zhuanlan.zhihu.com/p/457246453
package main;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
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.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicHeader;
import org.slf4j.Logger;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description: HttpClientTest
 * date: 2022/9/5 22:00
 * author: MR.孙
 */
public class HttpClientTest {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //获取HttpClient 对象
        //1.默认创建方式(获取默认配置的HttpClient)
        // CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.根据系统配置创建(根据系统配置创建HttpClient)
        // CloseableHttpClient httpClient = HttpClients.createSystem();

        //3.自定义创建(这种方式可以在创建时设置一些默认值)
        // CloseableHttpClient httpClient = HttpClients.custom()
        //         .setDefaultHeaders(Collections.<Header>emptyList())//设置默认表头
        //         .setDefaultRequestConfig(RequestConfig.DEFAULT)
        //         .build();//设置默认配置

        //创建配置对象
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000, TimeUnit.MILLISECONDS)//设置连接超时时间
                .setResponseTimeout(3000, TimeUnit.MILLISECONDS)//设置响应超时时间
                //设置从连接池获取连接的超时时间
                .setConnectionRequestTimeout(3000,TimeUnit.MILLISECONDS)
                .build();

        //创建Get请求对象
        HttpGet httpGet = new HttpGet("http://httpbin.org/get");
        //设置请求配置
        httpGet.setConfig(requestConfig);


        //设置请求头信息
        //1.设置公共请求头
        List<Header> headers = new ArrayList<>();
        //设置content-type类型
        headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON));
        //设置浏览器支持的编码
        headers.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip,x-gzip,deflate"));
        //是否是长连接
        headers.add(new BasicHeader(HttpHeaders.CONNECTION, "Keep-Alive"));


        //创建一个默认的httpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultHeaders(headers)
                .build();

        //2.为单个请求设置请求头
        httpGet.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED);
        httpGet.addHeader(new BasicHeader(HttpHeaders.ACCEPT, "*/*"));


        //发送请求
        //1.请求参数直接拼接在请求路径后面
        // String name = URLEncoder.encode("张三", "utf-8");
        // // 请求路径及参数
        // String url = "http://localhost:10010/user/params?age=20&name=" + name;

        // 调用 HttpClient 的 execute 方法执行请求
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 获取请求状态
            int code = response.getCode();
            System.out.println("请求的状态码为:->"+code);
            if(code == HttpStatus.SC_OK){
                System.out.println("请求成功......");
                System.out.println("响应结果为:->"+EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }}

package main;

import com.alibaba.fastjson.JSON;
import entity.User;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
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.*;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description: HttpClientTest
 * date: 2022/9/5 22:00
 * author: MR.孙
 */
public class HttpClientTest2 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //获取HttpClient 对象
        //1.默认创建方式(获取默认配置的HttpClient)
        // CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.根据系统配置创建(根据系统配置创建HttpClient)
        // CloseableHttpClient httpClient = HttpClients.createSystem();

        //3.自定义创建(这种方式可以在创建时设置一些默认值)
        // CloseableHttpClient httpClient = HttpClients.custom()
        //         .setDefaultHeaders(Collections.<Header>emptyList())//设置默认表头
        //         .setDefaultRequestConfig(RequestConfig.DEFAULT)
        //         .build();//设置默认配置

        //创建配置对象
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000, TimeUnit.MILLISECONDS)//设置连接超时时间
                .setResponseTimeout(3000, TimeUnit.MILLISECONDS)//设置响应超时时间
                //设置从连接池获取连接的超时时间
                .setConnectionRequestTimeout(3000,TimeUnit.MILLISECONDS)
                .build();



        //设置请求头信息
        //1.设置公共请求头
        List<Header> headers = new ArrayList<>();
        //设置content-type类型
        headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON));
        //设置浏览器支持的编码
        headers.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip,x-gzip,deflate"));
        //是否是长连接
        headers.add(new BasicHeader(HttpHeaders.CONNECTION, "Keep-Alive"));


        //创建一个默认的httpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultHeaders(headers)
                .build();




        // //2.为单个请求设置请求头
        // httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED);
        // httpPost.addHeader(new BasicHeader(HttpHeaders.ACCEPT, "*/*"));


        //创建Post请求对象
        HttpPost httpPost = new HttpPost("https://www.wanandroid.com/user/login");
        //设置请求配置
        httpPost.setConfig(requestConfig);
        //1.发送 JSON 数据
        // HttpClient 中发送 JSON 数据可以使用 StringHttpEntity 类实现
        User user = new User("admin","admin");

        //创建字符串实体对象
       HttpEntity httpEntity = new StringEntity(JSON.toJSONString(user));
       httpPost.setEntity(httpEntity);
       //发送Post请求
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取请求状态
            int code = response.getCode();
            System.out.println("请求的状态码为:->"+code);
            if(code == HttpStatus.SC_OK){
                System.out.println("请求成功......");
                System.out.println("响应结果为:->"+EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }}
posted @ 2022-09-05 22:59  长情c  阅读(266)  评论(0)    收藏  举报