JAVA模拟实现http的post请求使用json格式传参的实现方式

		***1.实现代码:***
		public void getPostMethod(String url){
		Map<String, Object> map = new HashMap<>();
		map.put("key1","value1");
		map.put("key2","value2");
		Map<String, Object> result = new HashMap<>();
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
		httpPost.addHeader("Content-type", "application/json; charset=utf-8");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
		HttpResponse response = httpClient.execute(httpPost);
		if (null == response || response.getStatusLine() == null) {
			throw new Exception("Post Request For Url[{}] is not ok. Response is null");
		} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			throw new Exception("Post Request For Url[{}] is not ok. Response Status Code is {}");
		}
		String resultString = EntityUtils.toString(response.getEntity());
		JSONObject jsonObj = JSONObject.parseObject(resultString);
		if (jsonObj.getInteger("STATUS") == 6) {
			result.put("STATUS", "success");
			result.put("FILEID", jsonObj.getInteger("FILEID"));
		} else {
			result.put("STATUS", "failed");
		}
		result.put("MESSAGE", jsonObj.getString("MSG"));
		return result;
		}

2.POM.xml需要添加的依赖:

org.apache.httpcomponents
httpclient
4.4


org.apache.httpcomponents
httpmime
4.4

		***时间:2020-10-29***
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值