前言
在实际开发过程中,我们经常是使用的POST发送application/json;charset=utf-8格式请求,但是有时候接口会设计成application/x-www-form-urlencoded,这就需要我们随机应变,改变请求方式,重新设计工具代码,这里贴出我在工作中使用的代码以供参考。
public static String postWithParamsForString(String url, HashMap<String, String> headers) {
List<NameValuePair> params = new ArrayList<>();
HttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
String msg = "";
try {
if (headers != null && headers.size() != 0) {
for (Map.Entry<String, String> entry : headers.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);
}
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
参数使用 HashMap<String, String> headers,需要大家将参数放置进新建的map中、map作为JAVA开发中重要的接口,需要重点掌握。
新建公众号,欢迎互关,共同进步。
标签:www,JAVA,String,form,headers,application,httpPost,new From: https://www.cnblogs.com/dajiangyang/p/16749747.html