maven依赖:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HttpClientUtils {
public HttpClientUtils() {
}
public static String doGet(String url, Map<String, String> headerMap) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建http GET请求
HttpGet httpGet = new HttpGet(url);
Iterator header = headerMap.entrySet().iterator();
while (header.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) header.next();
httpGet.addHeader(elem.getKey(), elem.getValue());
}
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doDelete(String url, Map<String, String> headers) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建http delete请求
HttpDelete httpDelete = new HttpDelete(url);
Iterator header = headers.entrySet().iterator();
while (header.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) header.next();
httpDelete.addHeader(elem.getKey(), elem.getValue());
}
// 执行请求
response = httpclient.execute(httpDelete);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param, String data) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
public static String doPostJson(String url, Map<String, String> headerMap, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
Iterator headerIterator = headerMap.entrySet().iterator(); //循环增加header
while (headerIterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
httpPost.addHeader(elem.getKey(), elem.getValue());
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
//dopostjson可以,这个目前还不行。
public static String doPostMap(String url, Map<String, String> headerMap, Map<String, String> contentMap) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
List<NameValuePair> content = new ArrayList<NameValuePair>();
Iterator iterator = contentMap.entrySet().iterator(); //将content生成entity
while (iterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) iterator.next();
content.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
CloseableHttpResponse response = null;
try {
Iterator headerIterator = headerMap.entrySet().iterator(); //循环增加header
while (headerIterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
post.addHeader(elem.getKey(), elem.getValue());
}
if (content.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content, "UTF-8");
post.setEntity(entity);
}
response = httpClient.execute(post); //发送请求并接收返回数据
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity(); //获取response的body部分
result = EntityUtils.toString(entity); //读取reponse的body部分并转化成字符串
}
return result;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
例子:
//发送post请求
//header用Map<String,String>构建。body用fastjson构建
//不知道为什么目前三个post方法只有这个dopostjson起作用,其他两个不能用。
String result = HttpClientUtils.doPostJson(URL, header, body);