HttpClient4Utils工具类

HttpClient4Utils是一个用于处理HTTP GET和POST请求的Java工具类,提供了简单的同步操作。请注意,异常处理部分需要根据实际项目需求进行定制。此外,使用此工具类需要引入特定的Maven依赖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意事项:
1、异常处理部分请大家根据项目结构自行调整
2、提供简单同步GET和POST方法
3、主要Maven依赖

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.6</version>
</dependency>
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @Author Dylan
 * @Date 2020/2/25
 */
public class HttpClient4Utils {

	private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient4Utils.class);

	public static final String APPLICATION_JSON_CHARSET_UTF_8 = "application/json;charset=utf-8";

	private static final RequestConfig REQUEST_CONFIG = RequestConfig.custom()
			// 设置连接超时时间(单位毫秒)
			.setConnectTimeout(1000 * 60)
			// 设置请求超时时间(单位毫秒)
			.setConnectionRequestTimeout(1000 * 60)
			// 设置socket读写超时时间(单位毫秒)
			.setSocketTimeout(1000 * 60)
			.build();

	public static String get(String url) {

		LOGGER.info("HTTP GET URL——" + url);

		// 创建GET请求
		HttpGet httpGet = new HttpGet(url);

		httpGet.setConfig(REQUEST_CONFIG);
		httpGet.setHeader("Content-Type", APPLICATION_JSON_CHARSET_UTF_8);

		try (
				// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
				CloseableHttpClient httpClient = HttpClients.createDefault();
				// 客户端执行(发送)GET请求
				CloseableHttpResponse httpGetResponse = httpClient.execute(httpGet)
		) {
			return handle(httpGetResponse);
		} catch (IOException e) {
			throw new AppException(HandleExceptionEnum.HTTP_ERROR, String.format("URL: {%s}", url), e);
		}
	}

	public static String post(String url) {

		LOGGER.info("HTTP POST URL——" + url);

		// 创建POST请求
		HttpPost httpPost = new HttpPost(url);

		httpPost.setConfig(REQUEST_CONFIG);
		httpPost.setHeader("Content-Type", APPLICATION_JSON_CHARSET_UTF_8);

		try (
				// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
				CloseableHttpClient httpClient = HttpClients.createDefault();
				// 客户端执行(发送)POST请求
				CloseableHttpResponse httpPostResponse = httpClient.execute(httpPost)
		) {
			return handle(httpPostResponse);
		} catch (IOException e) {
			throw new AppException(HandleExceptionEnum.HTTP_ERROR, String.format("URL: {%s}", url), e);
		}
	}

	private static String handle(CloseableHttpResponse httpResponse) throws IOException {
		StatusLine responseStatusLine = httpResponse.getStatusLine();
		LOGGER.info(String.format("Response Status Line: {%s}", responseStatusLine));

		// 从响应模型中获取响应实体
		HttpEntity responseEntity = httpResponse.getEntity();

		int statusCode = responseStatusLine.getStatusCode();
		if (isSuccessful(statusCode)) {
			if (Objects.nonNull(responseEntity)) {
				LOGGER.info("Success");
				LOGGER.info(String.format("Response Content Length: {%d}", responseEntity.getContentLength()));
				return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
			} else {
				throw new AppException(HandleExceptionEnum.HTTP_ERROR, "Response: {NULL}");
			}
		} else {
			LOGGER.error("Failure");
			if (Objects.nonNull(responseEntity)) {
				LOGGER.info(String.format("Response Content Length: {%d}", responseEntity.getContentLength()));
				LOGGER.error(EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
			}
			throw new AppException(HandleExceptionEnum.HTTP_ERROR, String.format("ResponseStatus: {%s}", statusCode));
		}
	}

	private static boolean isSuccessful(int statusCode) {
		return statusCode >= 200 && statusCode < 300;
	}

	public static void main(String[] args) {
		String resp = HttpClient4Utils.get("http://192.168.8.15:8088/ws/v1/cluster/scheduler");
		LOGGER.info(resp);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值