学习记录一种请求方式
逻辑:
简单
代码量:
偏多
维护:
所有的请求用的都是同样的链接配置(超时时间,代理等等),如果有特殊的(一个/一批)请求还需要特殊处理,业务逻辑方法还需要该配置
Http请求方式有多种所以需要调用者选择使用哪种请求方式,也可以提供一些固定的方法例如 getRest / postRest / delRest ...
这里直接使用三个方法
rest(入参) //用户调用的方法,根据自身业务逻辑增加参数,封装结果(根据业务逻辑封装结果数据,可以是JSON/XML ...)
getRequest(); //初始化创建一个Request对象,添加数据(请求类型/请求路径/请求头/请求体),配置链接(超时时间)
exec(); // 执行Request 获得Response对象,检验(返回的状态码),处理结果(将结果简单转换为String)
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>fluent-hcartifactId>
dependency>
package com.rs.testfield.rest;
import com.alibaba.fastjson.JSON;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import java.util.Map;
public class RequestClient {
public String rest() {
return exec(getRequest("get", "http://localhost:333/api/info", null, null));
}
private String exec(Request request) {
if (request == null) {
throw new RuntimeException("request is null");
}
try {
Response response = request.execute();
HttpResponse httpResponse = response.returnResponse();
int statusCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
return null;
}
String responseText = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
if (statusCode != 200) {
throw new RuntimeException(statusCode + ":" + responseText);
}
return responseText;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Request getRequest(String type, String url, Map<String, String> headers, Object body) {
Request request;
/**
* 对 Body的处理
*/
String bodyString = null;
if (body != null) {
bodyString = JSON.toJSONString(body);
}
switch (type) {
case "GET":
request = Request.Get(url);
break;
case "POST":
request = Request.Post(url);
if (StringUtils.isEmpty(bodyString)) {
request = request.bodyString(bodyString, ContentType.APPLICATION_JSON);
}
break;
case "PUT":
request = Request.Put(url);
if (StringUtils.isEmpty(bodyString)) {
request = request.bodyString(bodyString, ContentType.APPLICATION_JSON);
}
break;
case "DELETE":
request = Request.Delete(url);
break;
case "PATCH":
request = Request.Patch(url);
if (StringUtils.isEmpty(bodyString)) {
request = request.bodyString(bodyString, ContentType.APPLICATION_JSON);
}
break;
default:
throw new RuntimeException("未知的http请求方法 type=" + type);
}
/**
* 设置请求头
*/
if (headers != null) {
for (String key : headers.keySet()) {
String value = headers.get(key);
request.addHeader(key, value);
}
}
/**
* 对链接做一些配置 / 超时时间
*/
request.connectTimeout(3000);
request.socketTimeout(3000);
/**
* 设置代理
*/
request.viaProxy(new HttpHost("192.168.0.0", 30));
return request;
}
}