How to set HTTP header in RESTEasy client framework?

前端 未结 4 691
栀梦
栀梦 2021-01-31 11:19

RESTEasy (a JAX-RS implementation) has a nice client framework, eg:

RegisterBuiltin.register(ResteasyProviderFactory.getInstance());

SimpleClient client = Proxy         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-31 11:46

    With RestEasy 3.x I use ClientRequestFilters. In the below example there is a continuous integration (CI) server listening for requests running in the background. The test and the CI server use the same database and entity classes.

    Assume that a tenant named 'test-tenant' does in fact exist, and there is a user 'root' that belongs to that tenant, and the user has the password specified below.

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

    And the AddAuthHeadersRequestFilter class:

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

    The import statements (assuming you just paste the test and the static class into a single TestNg test-class file):

    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;
    

提交回复
热议问题