大家好,又见面了,我是你们的朋友全栈君。
最近项目中需要调用其他项目的Rest接口,之前一直在使用Apache的httpclient工具,该工具使用起来不是很方便,各种try{……} catch{……}结构,造成了代码量很大,而且有实际意义的代码却很少。
最近请教别人,学习使用RESTEasy工具,进行调用REST接口,极大地减少了调用Rest接口的代码,项目中仅需要一个RestEasyClient.java工具类即可,其他package中是需要调用REST接口时,仅需要直接调用即可,代码中仅有一个try{……} catch{……},很好的维护了项目代码的整洁和实用。
1.实战
RESTEasy的Maven依赖:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.7.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.19.Final</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.19.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>3.0.19.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>3.0.19.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-servlet-initializer</artifactId>
<version>3.0.19.Final</version>
</dependency>
RestEasyClient.java工具类:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.Response;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Created by lance.
*/
@Slf4j
public class RestEasyClient {
private static ResteasyClient client = null;
static {
ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder();
resteasyClientBuilder.connectionPoolSize(300);
resteasyClientBuilder.socketTimeout(5, TimeUnit.SECONDS);
resteasyClientBuilder.maxPooledPerRoute(200);
client = resteasyClientBuilder.build();
}
/**
* @param url url地址参数
* @return
*/
public static JSONObject get(String url, Map<String, Object> headers) {
Response response = null;
try {
ResteasyWebTarget target = client.target(url);
Invocation.Builder builder = target.request();
if (null != headers && !headers.isEmpty()) {
headers.entrySet().forEach(entry -> builder.header(entry.getKey(), entry.getValue()));
}
response = builder.get();
if (response != null) {
JSONObject jsonObject = response.readEntity(JSONObject.class);
log.info("http get result:{}", JSON.toJSONString(jsonObject));
return jsonObject;
}
} catch (Exception e) {
log.error("client.get() Error, url:{}", url);
log.error("client.get() Error", e);
} finally {
if (response != null) {
try {
response.close();
} catch (Exception e) {
log.error("client.close() Error", e);
}
}
}
return new JSONObject();
}
/**
* @param url url地址参数
* @param headers 请求中的header参数
* @param entity 请求的具体参数内容
* @param mediaType 之情请求的类型,如json
* @return
*/
public static JSONObject post(String url, Map<String, Object> headers, Object entity, String mediaType) {
log.info("client.post() INFO, url:{}, headers:{}, entity:{}, mediaType:{}", url, headers, entity, mediaType);
Response response = null;
try {
ResteasyWebTarget target = client.target(url);
Invocation.Builder builder = target.request();
if (null != headers && !headers.isEmpty()) {
headers.entrySet().forEach(entry -> builder.header(entry.getKey(), entry.getValue()));
}
response = builder.post(Entity.entity(entity, mediaType));
if (response != null) {
JSONObject jsonObject = response.readEntity(JSONObject.class);
log.info("http get result:{}", JSON.toJSONString(jsonObject));
return jsonObject;
}
} catch (Exception e) {
log.error("client.post() Error, url:{}, headers:{}, entity:{}, mediaType:{}", url, headers, entity, mediaType);
log.error("client.post() Error", e);
} finally {
if (response != null) {
try {
response.close();
} catch (Exception e) {
log.error("client.close() Error", e);
}
}
}
return new JSONObject();
}
Test类:
public class Test {
public static void main(String[] args) {
//get test
Map map = RestEasyClient.get("http://10.118.32.254:8801/data/rest/");
log.info("response:{}",map);
//post test
Map<String, Object> header = Maps.newHashMap();
header.put("userId", "1000");
Object item = new Object();
Map map = RestEasyClient.post("http://10.118.32.254:8801/data/rest/", header, Sets.newHashSet(item), MediaType.APPLICATION_JSON);
log.info("response:{}", map);
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/149577.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...