org.jboss.arquillian.drone.webdriver.utils.HttpClient Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of arquillian-drone-webdriver Show documentation
Show all versions of arquillian-drone-webdriver Show documentation
Extension for functional testing based on web view layer (Ajocado, Selenium, WebDriver)
package org.jboss.arquillian.drone.webdriver.utils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class HttpClient {
public static class Response {
private final String payload;
private final Map headers;
public Response(String payload, Map headers) {
this.payload = payload;
this.headers = headers;
}
public boolean hasPayload() {
return this.payload != null && !this.payload.isEmpty();
}
public String getPayload() {
return payload;
}
public String getHeader(String header) {
return headers.get(header);
}
public static Response from(HttpResponse response) throws IOException {
final HttpEntity entity = response.getEntity();
final String payload;
if (entity == null) {
payload = null;
} else {
payload = EntityUtils.toString(entity, "UTF-8");
}
final Map headers = new HashMap<>();
for (Header header : response.getAllHeaders()) {
headers.put(header.getName(), header.getValue());
}
return new Response(payload, headers);
}
}
public Response get(String url) throws IOException {
return get(url, Collections.emptyMap());
}
public Response get(String url, Map headers) throws IOException {
try (final CloseableHttpClient client = createHttpClient()) {
final HttpGet request = new HttpGet(url);
addHeaders(headers, request);
final HttpResponse response = client.execute(request);
return Response.from(response);
}
}
private CloseableHttpClient createHttpClient() {
final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.useSystemProperties();
return httpClientBuilder.build();
}
private void addHeaders(Map headers, HttpGet request) {
for (Map.Entry header : headers.entrySet()) {
request.addHeader(header.getKey(), header.getValue());
}
}
}