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

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

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);
	}
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页