话不多说,直接上代码。
public static String postXwwFormUrlEncoded(String url, HashMap<String, String> paraMap) throws IOException {
List<NameValuePair> params = new ArrayList<>();
HttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
String msg = "";
try {
if (paraMap != null && paraMap.size() != 0) {
for (Map.Entry<String, String> entry : paraMap.entrySet()) {
params.add(new NameValuePair() {
@Override
public String getName() {
return entry.getKey();
}
@Override
public String getValue() {
return entry.getValue();
}
});
}
}
httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpURLConnection.HTTP_OK == statusCode) {
HttpEntity entity = response.getEntity();
msg = EntityUtils.toString(entity);
}else {
return "{\"status\": \"0\",\"desc\": \"接口请求异常\"}";
}
} catch (IOException e) {
throw e;
}
return msg;
}
其中url为接口请求地址,paraMap为参数Map。注意上面写法需要引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>