2016-11-24 44 views
1

我正在尋找一種方法將包含參數名稱和值的映射傳遞給GET Web目標。我期待RESTEasy將我的地圖轉換爲URL查詢參數列表;但是,RESTEasy引發了一個異常,說Caused by: javax.ws.rs.ProcessingException: RESTEASY004565: A GET request cannot have a body. 。我如何告訴RESTEasy將此映射轉換爲URL查詢參數?如何使用RESTEasy代理客戶端發送查詢參數圖

這是代理接口:

@Path("/") 
@Consumes(MediaType.APPLICATION_JSON) 
public interface ExampleClient { 

    @GET 
    @Path("/example/{name}") 
    @Produces(MediaType.APPLICATION_JSON) 
    Object getObject(@PathParam("name") String name, MultivaluedMap<String, String> multiValueMap); 

} 

這是用法:

@Controller 
public class ExampleController { 

    @Inject 
    ExampleClient exampleClient; // injected correctly by spring DI 

    // this runs inside a spring controller 
    public String action(String objectName) { 
     MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); 

     // in the real code I get the params and values from a DB 
     params.add("foo", "bar") 
     params.add("jar", "car") 
     //.. keep adding 

     exampleClient.getObject(objectName, params); // throws exception 
    } 

} 

回答

1

小時後在的RESTEasy源代碼挖下來,我發現,有沒有辦法做到這一點,雖然界面註釋。簡而言之,RESTEasy從org.jboss.resteasy.client.jaxrs.internal.proxy.processors.ProcessorFactory創建一個稱爲「處理器」的東西,將註釋映射到目標URI。

但是,通過創建一個ClientRequestFilter來解決這個問題非常簡單,該請求從請求主體接收Map(在執行請求之前),並將它們放入URI查詢參數中。檢查以下的代碼:

濾波器:

@Provider 
@Component // because I'm using spring boot 
public class GetMessageBodyFilter implements ClientRequestFilter { 
    @Override 
    public void filter(ClientRequestContext requestContext) throws IOException { 
     if (requestContext.getEntity() instanceof Map && requestContext.getMethod().equals(HttpMethod.GET)) { 
      UriBuilder uriBuilder = UriBuilder.fromUri(requestContext.getUri()); 
      Map allParam = (Map)requestContext.getEntity(); 
      for (Object key : allParam.keySet()) { 
       uriBuilder.queryParam(key.toString(), allParam.get(key)); 
      } 
      requestContext.setUri(uriBuilder.build()); 
      requestContext.setEntity(null); 
     } 
    } 
} 

PS:我已經使用Map代替MultivaluedMap爲簡單起見

相關問題