httpClient5

1.httpClient5

<dependency>
    <groupId>org.apache.httpcomponents.client5groupId>
    <artifactId>httpclient5artifactId>
    <version>5.1.3version>
dependency>

<dependency>
    <groupId>org.apache.httpcomponents.client5groupId>
    <artifactId>httpclient5-fluentartifactId>
    <version>5.1.3version>
dependency>
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet;
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;

/**
 * @author giserDev
 * @description httpclient工具类
 * @date 2023-12-01 19:54:11
 */
@Slf4j
public class HttpUtil {

    private HttpUtil(){}

    public static String get(String url) {
        String resultContent = null;
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                // 获取状态码
                // HTTP/1.1
                log.info("version: {}", response.getVersion());
                // 200
                log.info("code: {}", response.getCode());
                // OK
                log.info("reasonPhrase: {}", response.getReasonPhrase());

                HttpEntity entity = response.getEntity();
                // 获取响应信息
                resultContent = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultContent;
    }

}
    @Test
    public void httpClientTest() {
        String result = HttpUtil.get("http://httpbin.org/get");
        System.out.println(result);
    }

你可能感兴趣的:(#,Java基础,java)