簡體   English   中英

在ClientRequestFilter中動態設置ClientRequestContext屬性

[英]set ClientRequestContext property dynamically in ClientRequestFilter

大家好,我只是想知道在jax-rs Web服務中使用ClientRequestFilter時如何將ClientRequestContext對象的屬性設置為動態值。 像這樣

假設我有一個對象

MyObject obj=new MyObject();
obj.nmae="simon";
obj.vendor=209;

現在我想調用一個為其創建球衣客戶端並為該客戶端創建篩選器的Web服務。現在我想知道如何將對象傳遞給clientFilter,以便可以將ClientRequestContext屬性設置為myObject?

 @Provider
    public class RequestClientFilter implements ClientRequestFilter {

        @Override
        public void filter(ClientRequestContext requestContext) throws IOException {
            // how to set this to a variable value passed from a function in my code
            requestContext.setProperty("test", "test client request filter");
         //something along these lines
        requestContext.setProperty("myobj",obj);
        }
    }

這就是正在發生的事情

 MyObject obj=new MyObject();
    obj.nmae="simon";
    obj.vendor=209;
         ClientConfig config = new ClientConfig();
            config.register(EntityLoggingFilter.class);
            config.register(GsonMessageBodyHandler.class);
            config.register(ClFilter.class);
            // config.property(ClientProperties.CONNECT_TIMEOUT, 1000);
            config.property(ClientProperties.READ_TIMEOUT, 10000);

            try {
                Client client = ClientBuilder.newClient(config);
                WebTarget webTarget = client.target("http://localhost:8081/ServicB").path("Register")
                        .path("Service");
                System.out.println(webTarget.getUri());
                Invocation.Builder invocationBuilder = webTarget.request().accept(MediaType.APPLICATION_JSON);
                Response response = invocationBuilder.post(Entity.json("anything"));
                System.out.println(response.getStatus());
                String bresponse = response.readEntity(String.class);
                if (bresponse == null) {
                    System.out.println("null response");
                }
                System.out.println(bresponse);

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

您可以將過濾器注冊為類或實例。 如果MyObject只是一次性對象,則只需將對象通過過濾器的構造函數,然后注冊即可。

config.register(new RequestClientFilter(myObject));

如果MyObject將針對每個請求進行更改,則您也可以向WebTarget注冊過濾器。 因此,對於每個不同的請求,您可以使用不同的對象。

Response response1 = client.target(uri)
    .register(new RequestClientFilter(myObjectOne))
    .request()
    .get();
Response response2 = client.target(uri)
    .register(new RequestClientFilter(myObjectTwo))
    .request()
    .get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM