Java发送httpPost请求--传消息头,消息体的方法

本文分享了在调用外部API接口时,如何使用HttpClient工具类发送包含消息头和消息体的POST请求。通过自定义sendPost方法,实现了传递JSON格式的数据,并提供了完整的代码示例。

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

HttpClient工具类拓展sendPost方法

最近开发中需要调外部厂商提供的API接口,接口文档中定义需要传递一个消息头+消息体。参考httpClient工具类中没有相关方法,所以自己写出来,并和大家分享。

代码来一波

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Map;
/**
* 
* @param url 接口地址
* @param headers 消息头
* @param data 消息体
* @return
*/
public static String sendPost(String url, Map<String, String> headers, String data) {
	String response = null;
	try {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse httpresponse = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(url);
			StringEntity stringentity = new StringEntity(data, ContentType.create("application/json", "UTF-8"));
			httppost.setEntity(stringentity);
			// 循环添加header
			Iterator headerIterator = headers.entrySet().iterator();
			while (headerIterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
				httppost.addHeader(elem.getKey(), elem.getValue());
			}
			//发post请求
			httpresponse = httpclient.execute(httppost);
			//utf-8参数防止中文乱码
			response = EntityUtils.toString(httpresponse.getEntity(), "utf-8");
		} finally {
			if (httpclient != null) {
				httpclient.close();
			}
			if (httpresponse != null) {
				httpresponse.close();
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return response;
}

测试该post方法

public static void main(String[] args) {
	// urlPath根据实际调用修改
	String urlPath = "/cdss/standard/api/v2";
	// 消息体的字符串
	String body = "{\"method\": \"cdss-kb-search\", \"query\": \"高血压\"" + ", \"params\": [{\"type\": \"药品\"}]}";
	// 定义消息头
	Map<String, String> headers = new HashMap<String, String>();
	headers.put("header1", "第一个消息头");
	try {
		// 调sendPost方法
		String result = sendPost("urlPath", headers, body);
		System.err.println(result);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

如果觉得对您有帮助,就赞赏一下吧,谢谢~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值