java发送http请求之一:HttpClients
作者:互联网
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
1.创建CloseableHttpClient 对象
CloseableHttpClient httpclient = HttpClients.createDefault();
2.如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数
// get创建uri,进行字符串的拼接
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// Post请求创建参数列表
if (param != null) {
//多处用于Java像url发送Post请求
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
//UrlEncodedFormEntity 的构造器在源码设计里只接受 List<? extends BasicNameValuePair> 等作为参数,不接受 Map
//要想封装 post 请求的参数,只能使用 List<BasicNameValuePair>
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
//键值对,被UrlEncodedFormEntity实例编码后变:param1=value1¶m2=value2的格式
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
3.创建请求方法的实例,并指定请求URL。
//创建HttpGet对象
HttpGet httpGet = new HttpGet(uri);
//创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
4.发送请求:execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
//get请求,执行请求
response = httpclient.execute(httpGet);
//post请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
5.调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6.对于返回数据可以进行初步处理
7.释放连接。无论执行方法是否成功,都必须释放连接
finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
标签:java,请求,HttpClients,get,http,param,key,new,HttpPost 来源: https://blog.csdn.net/dsaggdsd/article/details/119281903