通过路径和方法和编码集和参数利用httpclient发送请求的代码

这篇博客详细介绍了如何使用Java的HttpClient库发送HTTP请求。首先,通过一个名为sendURL的方法,传入URL、HTTP方法、参数和字符集来构建请求。接着,将参数转化为JSONObject并设置为请求实体。在响应处理中,根据状态码判断请求是否成功,并读取响应内容。此外,还定义了一个HttpWithBody类来扩展HttpEntityEnclosingRequestBase。最后,展示了如何封装和调用这些方法以执行实际的HTTP请求。

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

1、传入路径、方法、参数、编码集
public static SendGateWayResult sendURL(String urlParam, String method, Map<String, Object> params, String charset) {
StringBuilder resultBuffer = new StringBuilder();
HttpClient client = HttpClientBuilder.create().build();
SendGateWayResult sendGateWayResult=new SendGateWayResult();
BufferedReader br = null;
try {
HttpWithBody httpWthBody = new HttpWithBody(urlParam, method);
// 构建请求参数
JSONObject jsonObject = new JSONObject();
if (params != null && params.size() > 0) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
jsonObject.put(entry.getKey(), entry.getValue());
}
}
StringEntity formEntity = new StringEntity(jsonObject.toString(),charset);
formEntity.setContentType(“application/json”);
httpWthBody.setEntity(formEntity);
logger.info(“请求参数为:”+jsonObject.toString()+“请求地址:”+urlParam+",方法类型:"+method);
HttpResponse response = client.execute(httpWthBody);
int responseStatus = response.getStatusLine().getStatusCode();
logger.info(“sendURL responseStatus:”+responseStatus);
if(response!=null) {
HttpEntity entity = response.getEntity();
if(entity!=null) {
br = new BufferedReader(new InputStreamReader(entity.getContent()));
}
String temp;
if(br!=null) {
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
if (responseStatus == 200||responseStatus == 201||responseStatus == 204) {
//组装返回数据
sendGateWayResult.setResultCode(responseStatus+"");
sendGateWayResult.setResultError("");
sendGateWayResult.setResultMessage(resultBuffer.toString());
sendGateWayResult.setSuccess(true);
}else {
sendGateWayResult.setResultCode(responseStatus+"");
sendGateWayResult.setResultError(resultBuffer.toString());
sendGateWayResult.setResultMessage(resultBuffer.toString());
sendGateWayResult.setSuccess(false);
}
}
} catch (Exception e) {
logger.error(“请求kong网关失败!”, e);
sendGateWayResult.setResultCode(“500”);
sendGateWayResult.setSuccess(false);
sendGateWayResult.setResultError(“请求kong网关失败!:”+e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
logger.error(“关闭流失败!”, e);
}
}
}
return sendGateWayResult;
}
2、HttpWithBody 类的定义
public class HttpWithBody extends HttpEntityEnclosingRequestBase {
private String METHOD_NAME = “GET”;
public String getMethod() { return METHOD_NAME; }

public HttpWithBody(final String uri) {
    super();
    setURI(URI.create(uri));
}
public HttpWithBody(final URI uri) {
    super();
    setURI(uri);
}
public HttpWithBody() { super(); }

//
public HttpWithBody(final String uri, String method) {
    super();
    setURI(URI.create(uri));
    setMethod(method);
}
public void setMethod(String method)
{
	this.METHOD_NAME = method;
}

}

3、入口
KongServiceResult kongServiceResult=new KongServiceResult();
logger.info(“新增消费者信息传入参数为:”+consumerInfo);
String urlParam=kongGateWayAddress+“consumers/”;
//数据封装
try {
Map<String, Object> mapParams = TaskUtils.transformBeanToMap(consumerInfo);
kongServiceResult=TaskUtils.dealKongGateMethod(urlParam, mapParams, RestMethodEnum.POST+"", ConsumerInfo.class);
} catch (IllegalAccessException e) {
logger.error(“将javabean转换成map对象失败!”, e);
kongServiceResult.setReturnCode(“500”);
kongServiceResult.setSuccess(false);
kongServiceResult.setErrorMessage(“将javabean转换成map对象失败!”);
}
return kongServiceResult;
4、dealKongGateMethod方法的封装
public static KongServiceResult dealKongGateMethod( String urlParam,
Map<String, Object> mapParams,String restMethod,Class z) {
KongServiceResult kongServiceResult =new KongServiceResult();
//调用公共接口发送请求到kong网关
SendGateWayResult gateWayResult = TaskUtils.sendURL(urlParam,restMethod, mapParams, “UTF-8”);
logger.info(“请求路由信息返回参数:”+gateWayResult.toString());
//解析对象返回对象
if(gateWayResult.isSuccess()) {
Object parseObject=JSON.parseObject(gateWayResult.getResultMessage(), z);
if (parseObject != null) {
if (parseObject instanceof ArrayList) {
kongServiceResult.setObjects((List) parseObject);
} else {
kongServiceResult.setObject((T) parseObject);
}
}
}
//封装结果集返回
kongServiceResult.setReturnCode(gateWayResult.getResultCode());
kongServiceResult.setSuccess(gateWayResult.isSuccess());
kongServiceResult.setErrorMessage(gateWayResult.getResultError());
return kongServiceResult;

5、transformBeanToMap的封装
public static Map<String, Object> transformBeanToMap(Object object)
throws IllegalArgumentException, IllegalAccessException {
Map<String, Object> map = new HashMap<String, Object>();
if (object != null) {
Field[] declaredFields = object.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
Object value = field.get(object);
if(value==null) {
continue;
}
map.put(field.getName(), value);
}
}

	return map;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值