commons-httpclient-3.0.jar实现dopost请求

本文介绍了一个使用Java的HttpClient库发送POST请求,并将参数以JSON格式传递的方法。通过示例代码,展示了如何设置请求头、请求超时时间、构建JSON参数以及处理响应。

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

这个版本有点低,网上找的好多方法在这个包里边都没有方法,现在刚调通放过来记录下

public class HttpClientUtil extends BaseAction{

	public static String httpPostWithJSON(String url,Map<String, String> param){
		// TODO Auto-generated method stub
		//创建客户端
		HttpClient client = new HttpClient();
		//设置请求时间
		client.getHttpConnectionManager().getParams().setConnectionTimeout(15000);

		//判断地址是否存在
		if(url == null || url.trim().length() == 0 ) {
			log.error("URL is null");
		}

		//创建post请求方法实例
		PostMethod postMethod = new PostMethod(url);

		//设置时间
		postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
		postMethod.addRequestHeader("Content-Type", "application/json");

		String paramJson = "{ \r\n" + 
				"	\"callbackType\": \""+param.get("callbackType")+"\",\r\n" + 
				"  	\"businessId\": \""+param.get("businessId")+"\", \r\n" + 
				" 	\"state\": \""+param.get("state")+"\", \r\n" + 
				" 	\"remark\": \""+param.get("remark")+"\"\r\n" + 
				"}";


		try {
			//解析json格式
			RequestEntity entity = new StringRequestEntity(paramJson, "application/json", "UTF-8");
			postMethod.setRequestEntity(entity);
			log.debug(paramJson);

			int code = client.executeMethod(postMethod);
			log.debug(code);
			String res = postMethod.getResponseBodyAsString();
			postMethod.releaseConnection();
			log.debug(res);
			return res;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("POST请求发出失败,请求的地址为{"+url+"},参数为{"+paramJson+"},错误信息为{"+e.getMessage()+"}");
		}
		return null;
	}

然后写一个main方法测试下是否可行,我用的是百度首页的测试了下,返回的是整个页面信息

public static void main(String[] args) {
		//这里填写你想请求的地址或者接口
		String URL = "https://www.baidu.com/";
		Map<String, String> param = new HashMap<String, String>();
		param.put("callbackType", "01");
		param.put("businessId", "CTLDXE008679-C002-L20");
		param.put("state", "1");
		param.put("remark", "处理成功");
		//成功数据
		HttpClientUtil.httpPostWithJSON(URL,param);
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尉某人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值