public static final String DEFAULT_CODING = "UTF-8";post
public static String postUrlEncodeForm(String url,Map<String,Object> map,String coding) throws Exception {
if (null == coding || "".equals(coding)) {
coding = DEFAULT_CODING;
}
String result = "";
//處理請求參數
List<NameValuePair> valuePairs = new ArrayList<>();
for(Entry<String,Object> entry : map.entrySet()) {
NameValuePair valuePair = new BasicNameValuePair(entry.getKey(), toString(entry.getValue()));
valuePairs.add(valuePair);
}
//設置client參數
HttpClient client = HttpClientBuilder.create().build();
//發送請求
HttpPost post = new HttpPost(url);
HttpEntity entity = new UrlEncodedFormEntity(valuePairs,coding);
post.setEntity(entity);
HttpResponse response = client.execute(post);
//處理響應結果
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new RuntimeException("statusCode = [" + statusCode + "]");
} else {
HttpEntity respEntity = response.getEntity();
result = EntityUtils.toString(respEntity,coding);
}
return result;
}ui