JAVA HTTPPOST


public static String post(String url, Map<String, Object> paramMap) throws ClientProtocolException, IOException,Exception {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
//設置認證信息
JSONObject json=new JSONObject(paramMap);
httpPost.setConfig(RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(3000).setSocketTimeout(5000).build());
List<NameValuePair> formparams = setHttpParams(paramMap);
UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");
//通過setEntity()設置參數給post
httpPost.setEntity(param);
//利用httpClient的execute()方法發送請求並且獲取返回參數
HttpResponse response = httpClient.execute(httpPost);
String httpEntityContent = getHttpEntityContent(response);
httpPost.abort();
return httpEntityContent;
}
/**
* 設置請求參數
* @param
* @return
*/
private static List<NameValuePair> setHttpParams(Map<String, Object> paramMap) {
List<NameValuePair> formparams = new ArrayList<>();
Set<Map.Entry<String, Object>> set = paramMap.entrySet();
for (Map.Entry<String, Object> entry : set) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
return formparams;
}

/**
* 獲得響應HTTP實體內容
* @param response
* @return
* @throws java.io.IOException
* @throws java.io.UnsupportedEncodingException
*/
private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
//通過HttpResponse 的getEntity()方法獲取返回信息
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = br.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line + "\n");
line = br.readLine();
}
br.close();
is.close();
return sb.toString();
}
return "";
}


免責聲明!

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



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