【问题标题】:How to set HTTP header in RESTEasy client framework?如何在 RESTEasy 客户端框架中设置 HTTP 标头?
【发布时间】:2011-10-19 06:03:56
【问题描述】:

RESTEasy(一个 JAX-RS 实现)有一个不错的 client framework,例如:

RegisterBuiltin.register(ResteasyProviderFactory.getInstance());

SimpleClient client = ProxyFactory.create(SimpleClient.class, "http://localhost:8081");
client.putBasic("hello world");

如何设置 HTTP 标头?

澄清:

jkeeler 提出的解决方案是一个很好的方法,但我想在 ProxyFactory 级别设置 HTTP 标头,我不想将标头传递给客户端对象。有什么想法吗?

【问题讨论】:

    标签: java http-headers jax-rs resteasy


    【解决方案1】:

    在您的客户端代理界面中,使用@HeaderParam 注释:

    public interface SimpleClient
    {
       @PUT
       @Path("basic")
       @Consumes("text/plain")
       public void putBasic(@HeaderParam("Greeting") String greeting);
    }
    

    上面示例中的调用将添加一个如下所示的 HTTP 标头:

    Greeting: hello world
    

    【讨论】:

    • 谢谢,这是个好方法,但我正在寻找其他解决方案。我已经澄清了这个问题。
    • @jkeeler 正是我想要的?有一种简单的方法可以将我所有方法所需的这个参数放在这个接口中吗? tks
    • +1 对于这种方法 - 当需要标头时(即“授权”),在界面中指定它如此更简洁。
    【解决方案2】:

    我找到了解决办法:

    import org.apache.commons.httpclient.HttpClient;
    import org.jboss.resteasy.client.ClientRequest;
    import org.jboss.resteasy.client.ClientResponse;
    import org.jboss.resteasy.client.ProxyFactory;
    import org.jboss.resteasy.client.core.executors.ApacheHttpClientExecutor;
    import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
    import org.jboss.resteasy.spi.ResteasyProviderFactory;
    
    RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
    HttpClient httpClient = new HttpClient();
    ApacheHttpClientExecutor executor = new ApacheHttpClientExecutor(httpClient) {
        @Override
        public ClientResponse execute(ClientRequest request) throws Exception {
            request.header("X-My-Header", "value");
            return super.execute(request);
        }           
    };
    
    SimpleClient client = ProxyFactory.create(SimpleClient.class, "http://localhost:8081", executor);
    client.putBasic("hello world");
    

    【讨论】:

    • ProxyFactory 是如何知道你的执行者的?看起来令人不安的“魔法”。
    • @EricBowman - 你说得对,代码不正确。我已经修好了。您必须将executor 变量作为参数传递给ProxyFactory.create() 方法。
    【解决方案3】:

    在 RestEasy 3.x 中,我使用 ClientRequestFilters。在下面的示例中,有一个持续集成 (CI) 服务器侦听在后台运行的请求。测试和 CI 服务器使用相同的数据库和实体类。

    假设确实存在名为“test-tenant”的租户,并且存在属于该租户的用户“root”,并且该用户具有下面指定的密码。

    private static final String BASE_URI = "http://localhost:" + PORT;
    @Test(groups = "functionalTests")
    public void testGetTenant() throws Exception {
        Client client = ClientBuilder.newClient();
        ResteasyWebTarget target = (ResteasyWebTarget)client.target(BASE_URI);
        client.register(new AddAuthHeadersRequestFilter("root", "DefaultPasswordsAre:-("));
        TenantResource resource = target.proxy(TenantResource.class);
    
        RestTenant restTenant = resource.getTenant(tenant.id().value().toString());
    
        assertThat(restTenant.getName(), is("test-tenant"));
        assertThat(restTenant.isActive(), is(true));
    }
    

    还有 AddAuthHeadersRequestFilter 类:

    public static class AddAuthHeadersRequestFilter implements ClientRequestFilter {
    
        private final String username;
        private final String password;
    
        public AddAuthHeadersRequestFilter(String username, String password) {
            this.username = username;
            this.password = password;
        }
    
        @Override
        public void filter(ClientRequestContext requestContext) throws IOException {
            String token = username + ":" + password;
            String base64Token = Base64.encodeBase64String(token.getBytes(StandardCharsets.UTF_8));
            requestContext.getHeaders().add("Authorization", "Basic " + base64Token);
        }
    }
    

    导入语句(假设您只是将测试和静态类粘贴到单个 TestNg 测试类文件中):

    import javax.ws.rs.client.Client;
    import javax.ws.rs.client.ClientBuilder;
    import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
    import org.testng.annotations.Test;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import javax.ws.rs.client.ClientRequestContext;
    import javax.ws.rs.client.ClientRequestFilter;
    import org.apache.commons.codec.binary.Base64;
    

    【讨论】:

    【解决方案4】:

    更简单:

        ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target("https://test.com");
        Response response = target.request().header("Authorization", "Basic test123")
                .acceptEncoding("gzip, deflate")
                .post(Entity.entity(some_xml, "application/x-www-form-urlencoded"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      相关资源
      最近更新 更多