關於 http 接口請求第三方接口 的demo(post方式帶參數)


/**
* 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方法的使用,百度都有。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM