使用HttpClient发送请求、接收响应很简单,一般需要以下几步:
1.通过maven导入依赖的JAR包。
2.创建CloseableHttpClient对象。
3.如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4.调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5.调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6.释放连接。无论执行方法是否成功,都必须释放连接。
导入maven依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>
后台代码:
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
/**
* 发送post请求
* @param url
* @param soapRequestXml
* @return
* @throws Exception
*/
public static String sendPostSoapXml(String url, String soapRequestXml) throws Exception {
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectionRequestTimeout(60000)
.setConnectTimeout(60000)
.build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
//设置post请求方式为SOAP+XML
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
StringEntity data = new StringEntity(soapRequestXml, Charset.forName("UTF-8"));
httpPost.setEntity(data);
//发送post请求
response = closeableHttpClient.execute(httpPost);
if (response == null || response.getStatusLine() == null) {
throw new RuntimeException("发送POST请求失败,返回结果为空!");
}
//返回状态是否200
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
//得到请求结果
HttpEntity entityRes = response.getEntity();
if (entityRes != null) {
String responsetData = EntityUtils.toString(entityRes, "UTF-8");
return responsetData;
}
} else {
throw new Exception("发送POST-SOAP+XML请求出错:" + response);
}
} catch (Exception e) {
throw new Exception("发送POST请求出现异常,"+e.getMessage());
} finally {
try {
// 关闭连接释放资源
if (response != null) {
response.close();
}
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
/**
* 发送post请求
* @param url
* @param requestJson
* @return
* @throws Exception
*/
public static String sendPostJson(String url, String requestJson) throws Exception {
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectionRequestTimeout(60000)
.setConnectTimeout(60000)
.build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
//设置post请求方式为JSON
httpPost.addHeader("Authorization", "Basic" + encryptBASE64("username", "password"));
StringEntity data = new StringEntity(requestJson, "UTF-8");
data.setContentType("application/json; charset=UTF-8");
httpPost.setEntity(data);
//发送post请求
response = closeableHttpClient.execute(httpPost);
if (response == null || response.getStatusLine() == null) {
throw new Exception("发送POST请求失败,返回结果为空!");
}
//返回状态是否200
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
//得到请求结果
HttpEntity entityRes = response.getEntity();
if (entityRes != null) {
String responsetData = EntityUtils.toString(entityRes, "UTF-8");
return responsetData;
}
} else {
throw new Exception("发送POST-JSON请求出错:" + response);
}
} catch (Exception e) {
throw new Exception("发送POST请求出现异常,"+e.getMessage());
} finally {
try {
// 关闭连接释放资源
if (response != null) {
response.close();
}
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
public static String encryptBASE64(String username, String password) {
byte[] key = (username+":"+password).getBytes();
return new String(Base64.encodeBase64(key));
}
}