准备工作
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
创建HttpUtils.java
public class HttpUtils {
private final static Logger logger = LoggerFactory.getLogger("-----HttpUtils-----");
private final static int RESULT_OK = 200;
private Map<String, String> headers;
private CloseableHttpClient client;
private HttpUtils() {
}
public static HttpUtils create() {
return new HttpUtils();
}
public HttpUtils client(CloseableHttpClient client) {
this.client = client;
return this;
}
public HttpUtils headers(Map<String, String> headers) {
this.headers = headers;
return this;
}
public String get(String url) {
try {
return getResult(url);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getDownLoad(String url, String dir, String name) {
try {
return downLoadFile(url, dir, name);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String post(String url, Map<String, Object> param) {
HttpEntity entity = new UrlEncodedFormEntity(createParam(param), Consts.UTF_8);
try {
return postResult(url, entity);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String post(String url, String param) {
HttpEntity entity = new StringEntity(param, Consts.UTF_8);
try {
return postResult(url, entity);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String postDownLoad(String url, String param, String dir, String name) {
HttpEntity entity = new StringEntity(param, Consts.UTF_8);
try {
return downLoadFile(url, entity, dir, name);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public RequestConfig config() {
// 配置信息
return RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
}
private String postResult(String url, HttpEntity entity) throws Exception {
HttpPost post = new HttpPost(url);
if (null != headers && !headers.isEmpty()) {
headers.forEach(post::addHeader);
}
CloseableHttpClient httpClient = null != client ? client : HttpClientBuilder.create().build();
post.setConfig(config());
post.setEntity(entity);
return getResultString(httpClient.execute(post));
}
private String getResult(String url) throws Exception {
CloseableHttpClient httpClient = null != client ? client : HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
if (null != headers && !headers.isEmpty()) {
headers.forEach(get::addHeader);
}
get.setConfig(config());
return getResultString(httpClient.execute(get));
}
private String downLoadFile(String url, HttpEntity entity, String dir, String name) throws Exception {
CloseableHttpClient httpClient = null != client ? client : HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
if (null != headers && !headers.isEmpty()) {
headers.forEach(post::addHeader);
}
post.setConfig(config());
post.setEntity(entity);
return download(httpClient.execute(post), dir, name);
}
private String downLoadFile(String url, String dir, String name) throws Exception {
CloseableHttpClient httpClient = null != client ? client : HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
if (null != headers && !headers.isEmpty()) {
headers.forEach(get::addHeader);
}
get.setConfig(config());
return download(httpClient.execute(get), dir, name);
}
private String getResultString(CloseableHttpResponse execute) throws IOException {
try (CloseableHttpResponse response = execute) {
HttpEntity httpEntity = response.getEntity();
int code = response.getStatusLine().getStatusCode();
String result = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
logger.debug(result);
if (RESULT_OK == code) {
return result;
} else {
return null;
}
}
}
private String download(CloseableHttpResponse execute, String dir, String name) throws IOException {
try (CloseableHttpResponse response = execute) {
HttpEntity httpEntity = response.getEntity();
File dirs = new File(dir);
if (!dirs.exists()) {
dirs.mkdirs();
}
File file = new File(dirs.getAbsolutePath(), name);
FileUtils.copyInputStreamToFile(httpEntity.getContent(), file);
return dirs.getAbsolutePath() + "/" + name;
}
}
private static List<NameValuePair> createParam(Map<String, Object> param) {
//建立一个NameValuePair数组,用于存储欲传送的参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (param != null) {
for (String k : param.keySet()) {
logger.debug(k + ":" + param.get(k).toString());
nvps.add(new BasicNameValuePair(k, param.get(k).toString()));
}
}
return nvps;
}
public static void main(String[] args) {
String url = WxUtils.ACCESS_TOKEN;
url = url.replace("APPID", "xxxxxxxxxxxxxxx");
url = url.replace("APPSECRET", "xxxxxxxxxx");
String ret = HttpUtils.create().get(url);
System.out.println(ret);
}
}
调用结果
获取微信AccessToken
{"access_token":"xx_xXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","expires_in":7200}
网友评论