RestEasy 调用Rest接口使用详解

        最近项目中需要调用其他项目的Rest接口,之前一直在使用Apache的httpclient工具,该工具使用起来不是很方便,各种try{......} catch{......}结构,造成了代码量很大,而且有实际意义的代码却很少。

       最近请教别人,学习使用RESTEasy工具,进行调用REST接口,极大地减少了调用Rest接口的代码,项目中仅需要一个RestEasyClient.java工具类即可,其他package中是需要调用REST接口时,仅需要直接调用即可,代码中仅有一个try{......} catch{......},很好的维护了项目代码的整洁和实用。

1.实战

RESTEasy的Maven依赖:

 
            org.jboss.resteasy
            jaxrs-api
            3.0.7.Final
        
        
            org.jboss.resteasy
            resteasy-jaxrs
            3.0.19.Final
            
        
        
            org.jboss.resteasy
            resteasy-client
            3.0.19.Final
        
        
            org.jboss.resteasy
            resteasy-multipart-provider
            3.0.19.Final
            provided
        
        
            org.jboss.resteasy
            resteasy-jackson2-provider
            3.0.19.Final
        
        
            org.jboss.resteasy
            resteasy-servlet-initializer
            3.0.19.Final
        


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 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 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 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);
	
	}
	
}








你可能感兴趣的:(Java)