项目依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.35</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
</dependencies>
模拟get请求
public static String get(String url, Map<String, String> params) {
String respString = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
try {
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity httpEntity = response.getEntity();
respString = EntityUtils.toString(httpEntity);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
}
}
return respString;
}
模拟post请求
public static String postForm(String url, Map<String, String> form) {
String respString = "";
List<NameValuePair> formParams = new ArrayList<>();
Set<Map.Entry<String, String>> entries = form.entrySet();
Iterator<Map.Entry<String, String>> it = entries.iterator();
while (it.hasNext()) {
Map.Entry<String, String> next = it.next();
String key = next.getKey();
String value = next.getValue();
formParams.add(new BasicNameValuePair(key, value));
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
HttpPost request = new HttpPost(url);
request.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(request);
request.abort();//释放post请求
if (response.getStatusLine().getStatusCode() == 302) {
String locationUrl = response.getLastHeader("Location").getValue();
respString = get(locationUrl, null);//跳转到重定向的url
} else if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = response.getEntity();
respString = EntityUtils.toString(httpEntity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
}
}
return respString;
}
模拟getJson请求
public static String get(String url, Map<String, String> params) {
String respString = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
try {
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity httpEntity = response.getEntity();
respString = EntityUtils.toString(httpEntity);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
}
}
return respString;
}
模拟postJson请求
public static String postJson(String url, String json) {
String resultJson = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
StringEntity entity = new StringEntity(json, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("UTF-8");
httppost.setEntity(entity);
response = httpclient.execute(httppost);
HttpEntity result = response.getEntity();
resultJson = EntityUtils.toString(result, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
}
return resultJson;
}
模拟异步postJson请求
public static String postJsonAsync(String url, String json, Integer timeOut, Class<? extends FutureCallback<HttpResponse>> clazz) {
if (timeOut == null || timeOut < 0) {
timeOut = 5000;
}
String resultJson = "";
// 创建默认的httpClient实例.
final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
// 创建httppost
httpclient.start();
FutureCallback<HttpResponse> futureCallback = null;
try {
Constructor<? extends FutureCallback<HttpResponse>> declaredConstructor = clazz.getDeclaredConstructor(CloseableHttpAsyncClient.class);
futureCallback = declaredConstructor.newInstance(httpclient);
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
final HttpPost httppost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(2000).build();// 设置请求和传输超时时间
httppost.setConfig(requestConfig);
try {
StringEntity entity = new StringEntity(json, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httppost.setEntity(entity);
httpclient.execute(httppost, futureCallback);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultJson;
}
模拟使用异步postJson
public static void main(String[] args) {
postJsonAsync("url", "{'a':1}", 50, CallBack.class);
}
static class CallBack implements FutureCallback<HttpResponse> {
private CloseableHttpAsyncClient httpclient;
public CallBack(CloseableHttpAsyncClient httpclient) {
this.httpclient = httpclient;
}
@Override
public void completed(HttpResponse response) {
HttpEntity result = response.getEntity();
try {
String resultJson = EntityUtils.toString(result, "UTF-8");
System.out.println(resultJson);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(Exception ex) {
}
@Override
public void cancelled() {
}
}