Как установить HTTP-заголовок в resteasy client framework?
RESTEasy (реализация JAX-RS) имеет хороший база клиентов, например:
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
SimpleClient client = ProxyFactory.create(SimpleClient.class, "http://localhost:8081");
client.putBasic("hello world");
Как вы устанавливаете заголовки HTTP?
пояснение:
решение, предложенное jkeeler - хороший подход, но я хочу установить HTTP-заголовки на уровне ProxyFactory, и я не хочу передавать заголовки объекту клиента. Есть идеи?
4 ответов
С 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;
в клиентском прокси-интерфейсе используйте @HeaderParam
аннотация:
public interface SimpleClient
{
@PUT
@Path("basic")
@Consumes("text/plain")
public void putBasic(@HeaderParam("Greeting") String greeting);
}
вызов в вашем примере выше добавит заголовок HTTP, который выглядит следующим образом:
Greeting: hello world
Я нашел решение:
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");
еще проще:
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"));