/**
* json格式提交參數
* @param uri 接口地址
* @param params 參數
* @param token
* @return
* @throws IOException
*/
public static String doJsonPost(String uri, String params,String token) throws IOException {
// 創建一個post請求
HttpPost post = new HttpPost(uri);
post.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
post.setHeader("Content-Type", "application/json");
String result=null;
//設置參數
if(!StringUtils.isBlank(params)){post.setEntity(new StringEntity(params, "utf-8"));}
//設置
if(!StringUtils.isBlank(token)){post.setHeader("token",token);}
//創建客戶端
HttpClient httpClient = HttpClients.createDefault();
//發送請求
HttpResponse response = httpClient.execute(post);
result=getCodeAndResult(response);
return result;
}
/**
* 根據響應結果獲取狀態碼和body
*
* @param response 響應結果
* @throws IOException
*/
private static String getCodeAndResult(HttpResponse response) throws IOException {
// 獲取狀態碼
//int code = response.getStatusLine().getStatusCode();
//System.out.println(code);
// 獲取body
return EntityUtils.toString(response.getEntity());
}
在設置 頭的 時候 要注意 set和 add方法的使用,百度都有。