一、JavaHttpRequest简介
JavaHttpRequest是一款基于Java语言开发的http请求工具,可以用于实现Java程序对HTTP接口进行调用。它支持多种请求方法、参数设置、数据传输等,使用简单方便,而且还提供了丰富的回调函数,方便用户对响应数据进行处理。
二、JavaHttpRequest的使用
1、引入JavaHttpRequest库
在使用JavaHttpRequest之前,需要先引入相关的库文件。我们通过maven来引入:
org.apache.httpcomponents
httpclient
4.5.13
org.apache.httpcomponents
httpmime
4.5.13
org.apache.httpcomponents
httpcore
4.4.13
com.alibaba
fastjson
1.2.62
org.projectlombok
lombok
1.18.22
provided
org.slf4j
slf4j-api
1.7.32
2、JavaHttpRequest请求示例
下面我们给出JavaHttpRequest的具体使用示例:
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
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.util.EntityUtils;
import java.io.IOException;
@Slf4j
public class HttpRequest {
public static final String METHOD_GET = "GET";
public static final String METHOD_POST = "POST";
public static final String METHOD_PUT = "PUT";
public static final String METHOD_DELETE = "DELETE";
/**
* 发送HTTP请求
*
* @param url
* @param method
* @param headers
* @param params
* @return
*/
@SneakyThrows
public static HttpResponseEntity doHttpRequest(String url, String method, JSONObject headers, JSONObject params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse;
if (METHOD_GET.equals(method)) { // GET
String queryString = RequestParamsUtil.getQueryString(params);
HttpGet httpGet = new HttpGet(url + "?" + queryString);
for (String key : headers.keySet()) {
httpGet.setHeader(key, headers.getString(key));
}
httpResponse = httpClient.execute(httpGet);
} else if (METHOD_POST.equals(method)) { // POST
HttpPost httpPost = new HttpPost(url);
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.getString(key));
}
StringEntity entity = new StringEntity(params.toJSONString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
} else if (METHOD_PUT.equals(method)) { // PUT
HttpPut httpPut = new HttpPut(url);
for (String key : headers.keySet()) {
httpPut.setHeader(key, headers.getString(key));
}
StringEntity entity = new StringEntity(params.toJSONString(), ContentType.APPLICATION_JSON);
httpPut.setEntity(entity);
httpResponse = httpClient.execute(httpPut);
} else if (METHOD_DELETE.equals(method)) { // DELETE
HttpDelete httpDelete = new HttpDelete(url);
for (String key : headers.keySet()) {
httpDelete.setHeader(key, headers.getString(key));
}
httpResponse = httpClient.execute(httpDelete);
} else {
throw new RuntimeException("http method not support");
}
HttpResponseEntity res = new HttpResponseEntity();
res.setStatusCode(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
res.setContent(EntityUtils.toString(httpEntity, "UTF-8"));
}
return res;
}
/**
* 发送HTTP请求
*
* @param url
* @param method
* @param headers
* @param payload
* @return
* @throws IOException
*/
public static String doHttpRequest(String url, String method, JSONObject headers, String payload) throws IOException {
HttpEntityEnclosingRequestBase requestBase = null;
if (method.equalsIgnoreCase("post")) {
requestBase = new HttpPost(url);
} else if (method.equalsIgnoreCase("put")) {
requestBase = new HttpPut(url);
} else if (method.equalsIgnoreCase("delete")) {
requestBase = new HttpDeleteWithBody(url);
}
for (String key : headers.keySet()) {
requestBase.setHeader(key, headers.getString(key));
}
if (payload != null && !payload.isEmpty()) {
requestBase.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
}
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpResponse response = httpclient.execute(requestBase);
String result = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
httpclient.close();
return result;
}
}
三、JavaHttpRequest的参数设置
1、HTTP请求头设置
使用JavaHttpRequest进行请求时,可能需要设置HTTP请求头,可以通过以下方法来实现:
JSONObject headers = new JSONObject();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + token);
HttpResponseEntity responseEntity = HttpRequest.doHttpRequest(url, "POST", headers, requestBody);
log.info(responseEntity.getContent());
2、HTTP请求参数设置
除了设置HTTP请求头之外,我们还需要设置HTTP请求参数,在JavaHttpRequest中,我们可以使用JSONObject对象来设置请求参数,具体示例如下:
JSONObject params = new JSONObject();
params.put("username", "admin");
params.put("password", "123456");
HttpResponseEntity responseEntity = HttpRequest.doHttpRequest(url, "POST", null, params);
log.info(responseEntity.getContent());
四、JavaHttpRequest的响应处理
1、获取HTTP响应码
在JavaHttpRequest中,我们可以通过HttpResponseEntity对象来获取HTTP响应码,具体示例如下:
HttpResponseEntity responseEntity = HttpRequest.doHttpRequest(url, "GET", null, null);
int statusCode = responseEntity.getStatusCode();
log.info("statusCode: {}", statusCode);
2、获取HTTP响应头
除了获取HTTP响应码之外,我们还可以获取HTTP响应头信息,具体示例如下:
HttpResponseEntity responseEntity = HttpRequest.doHttpRequest(url, "GET", null, null);
Map
headers = responseEntity.getHeaders();
for (String key : headers.keySet()){
log.info(key + ": " + headers.get(key));
}
3、获取HTTP响应内容
最重要的是获取HTTP响应内容,JavaHttpRequest提供了很多种获取响应内容的方法,包括获取字符串、文件、流等,具体示例如下:
HttpResponseEntity responseEntity = HttpRequest.doHttpRequest(url, "POST", headers, requestBody);
String content = responseEntity.getContent(); // 获取响应字符串
log.info("response content: {}", content);
此外,JavaHttpRequest还提供了其他的处理方法,如获取响应流、获取响应文件等,具体请参见官方文档。
五、JavaHttpRequest的异常处理
在JavaHttpRequest中,如果请求失败或出现异常,会抛出异常,我们需要对异常进行捕获和处理,具体示例如下:
try {
HttpResponseEntity responseEntity = HttpRequest.doHttpRequest(url, "GET", null, null);
int statusCode = responseEntity.getStatusCode();
log.info("statusCode: {}", statusCode);
} catch (Exception e) {
log.error("http request error", e);
}
六、小结
JavaHttpRequest是一款优秀的http请求工具,支持多种请求方法、参数设置、数据传输等,并提供了丰富的回调函数,方便用户对响应数据进行处理。本文从JavaHttpRequest的介绍、使用、参数设置、响应处理以及异常处理等多个方面进行详细介绍,希望能够对广大Java开发者有所帮助。