Get请求:
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
//参数Map
Map<String,String> param = new HashMap<>();
param.put("xx",xxxx);
//请求头
Map<String,String> headers= new HashMap<>();
headers.put("xx",xxxx);
//结果集转换
ObjectMapper mapper = new ObjectMapper();
try {
// 创建uri
URIBuilder builder = new URIBuilder("url");
//传递参数
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
//传递请求头
if (headers != null) {
for (String key : headers.keySet()) {
httpGet.addHeader(key,headers.get(key));
}
}
httpGet.addHeader("Accept-Charset", "utf-8");
httpGet.addHeader("contentType", "utf-8");
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0");
httpGet.addHeader("Content-Type", "application/json");
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
JsonNode rootNode = mapper.readTree(result);
//根据需求取对应数据
String xxx = rootNode.get("xxxxx").asText();
}
} catch (Exception e) {
e.printStackTrace();
log.error("", e);
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Post请求:
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
// 参数Map 存入body体
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put(key ,value)
String param = objectNode.toString();
//请求头
Map<String,String> headers= new HashMap<>();
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
//添加请求头
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.addHeader(key,headers.get(key));
}
}
httpPost.addHeader("Accept-Charset", "utf-8");
httpPost.addHeader("contentType", "utf-8");
httpPost.addHeader("Content-Type", "application/json");
//添加请求体
StringEntity entity = new StringEntity(param, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
xxx
} finally {
xxxx
}
本文详细描述了如何使用ApacheHttpClient库在Java中实现HTTPGET和POST请求,包括构建请求、设置参数、头信息以及处理响应结果的过程。
1032

被折叠的 条评论
为什么被折叠?



