方法一:可以将param放在实体里面
public static String dopostJson(String url, String param, String token) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("TT", token);
String charSet = "UTF-8";
StringEntity entity = new StringEntity(param, charSet);
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String getentity = EntityUtils.toString(response.getEntity());
JSONObject responseResult = JSONObject.parseObject(getentity);
// System.out.println(("请求响应结果:" + responseResult));
String result = "";
if (responseResult.get("code").equals("200")) {
result = responseResult.getString("data");
// System.out.println("打印data:" + result);
}
else{
String msg = responseResult.getString("msg");
System.out.println("接口报错:" + msg);
}
return result;
}
方法二:也可以直接拼接在url后面
public static String dopost(String url, String param, String token) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url + "?" + param);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("TT", token);
HttpResponse response = httpclient.execute(httpPost);
String getentity = EntityUtils.toString(response.getEntity());
JSONObject responseResult = JSONObject.parseObject(getentity);
// System.out.println(("请求响应结果:" + responseResult));
String result = "";
if (responseResult.get("code").equals("200")) {
result = responseResult.getString("data");
// System.out.println("打印data:" + result);
}
else{
String msg = responseResult.getString("msg");
System.out.println("接口报错:" + msg);
}
return result;
}