java实现:
public static String doPostForm(String url, Map map) {
String strResult = "";
// 1. 获取默认的client实例
CloseableHttpClient client = HttpClients.createDefault();
// 2. 创建httppost实例
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
// 3. 创建参数队列(键值对列表)
List paramPairs = new ArrayList<>();
Set keySet = map.keySet();
for (String key : keySet) {
Object val = map.get(key);
paramPairs.add(new BasicNameValuePair(key, val.toString()));
}
UrlEncodedFormEntity entity;
try {
// 4. 将参数设置到entity对象中
entity = new UrlEncodedFormEntity(paramPairs, "UTF-8");
System.out.println("封装的参数:"+entity);
// 5. 将entity对象设置到httppost对象中
httpPost.setEntity(entity);
// 6. 发送请求并回去响应
CloseableHttpResponse resp = client.execute(httpPost);
try {
// 7. 获取响应entity
HttpEntity respEntity = resp.getEntity();
strResult = EntityUtils.toString(respEntity, "UTF-8");
} finally {
// 9. 关闭响应对象
resp.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 10. 关闭连接,释放资源
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return strResult;
}
第二种方式:
导入依赖:
org.apache.httpcomponents
httpmime
4.5.8
commons-httpclient
commons-httpclient
3.1
public static String sendPostRequest(String url, Map params, Map header) {
try {
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("Content-Type", AppConsts.CONTENT_TYPE_FORM + ";charset=" + AppConsts.ENCODING_UTF8);
if (!CollectionUtils.isEmpty(header)){
header.forEach(postMethod::setRequestHeader);
}
NameValuePair[] data = new NameValuePair[params.size()];
int i = 0;
for (String key : params.keySet()) {
data[i] = new NameValuePair(key, params.get(key) == null ? "" : params.get(key).toString());
i++;
}
postMethod.setRequestBody(data);
HttpClient httpClient = new HttpClient();
int response = httpClient.executeMethod(postMethod); // 执行POST方法
String result = postMethod.getResponseBodyAsString();
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}



