Post路径请求参数在java体中实现方式
- 使用Map进行参数的封装
Map<String, Object> map = new HashMap<>(4);
map.put("param1", param1);
map.put("param2", param2);
map.put("param3", param3);
...
- 发送请求
try{
post = this.post(url, map);
jsonObject = JSONObject.parseObject(post);
errcode = (String) jsonObject.get("errcode");
if(StringUtils.isNotEmpty(errcode)) {
}
}catch (Exception e){
log.error(""+e);
}
- post方法实现
public static String post(String uri, Map<String, Object> params) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
CloseableHttpResponse response = null;
try {
List<BasicNameValuePair> parameters = Lists.newArrayList();
Set<Map.Entry<String, Object>> enties = params.entrySet();
for(Map.Entry<String, Object> entry : enties) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "utf-8");
httpPost.setEntity(formEntity);
response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
String result = null;
result = EntityUtils.toString(httpEntity);
return result;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (httpclient != null) {
httpclient.close();
httpclient = null;
}
if (httpPost != null) {
httpPost.releaseConnection();
httpPost = null;
}
if (response != null) {
response.close();
response = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
|