CloseableHttpClient httpClient = HttpClients.createDefault();
try {
//创建一个获取连接客户端的工具
URIBuilder builder = new URIBuilder(url);
//拼接url参数
builder.addParameter("token","");
URI uri = builder.build();
//创建Post请求、设置请求类型
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//需要的参数
Map<String,String> map = new HashMap<>();
map.put("","");
map.put("","");
...
//拼接参数体
List<NameValuePair> paramList=new ArrayList<NameValuePair>();
for(Map.Entry<String, String> entry : map.entrySet()){
paramList.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(paramList,"UTF-8"));
try {
//发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
org.apache.http.HttpEntity httpEntity = response.getEntity();
//返回状态码200表示请求成功
if (response.getStatusLine().getStatusCode() == 200) {
JSONObject resultString = (JSONObject) JSONObject.parse(EntityUtils.toString(response.getEntity(), "UTF-8"));
return Result.ok(JSONObject.toJSON(resultString));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (URISyntaxException | UnsupportedEncodingException e) {
e.printStackTrace();
}
Java Http(application/x-www-form-urlencoded)post请求方式代码示例
于 2023-02-21 14:58:02 首次发布