use of io.irontest.core.teststep.HTTPAPIResponse in project irontest by zheng-wang.
the class IronTestUtils method invokeHTTPAPI.
/**
* This method trusts all SSL certificates exposed by the API.
*
* @param url
* @param username
* @param password
* @param httpMethod
* @param httpHeaders
* @param httpBody
* @return
* @throws Exception
*/
public static HTTPAPIResponse invokeHTTPAPI(String url, String username, String password, HTTPMethod httpMethod, List<HTTPHeader> httpHeaders, String httpBody) throws Exception {
UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" }, UrlValidator.ALLOW_LOCAL_URLS);
if (!urlValidator.isValid(url)) {
throw new RuntimeException("Invalid URL");
}
// to allow special characters like whitespace in query parameters
String safeUrl = UrlEscapers.urlFragmentEscaper().escape(url);
// create HTTP request object and set body if applicable
HttpUriRequest httpRequest;
switch(httpMethod) {
case GET:
httpRequest = new HttpGet(safeUrl);
break;
case POST:
HttpPost httpPost = new HttpPost(safeUrl);
// StringEntity doesn't accept null string (exception is thrown)
httpPost.setEntity(httpBody == null ? null : new StringEntity(httpBody, "UTF-8"));
httpRequest = httpPost;
break;
case PUT:
HttpPut httpPut = new HttpPut(safeUrl);
// StringEntity doesn't accept null string (exception is thrown)
httpPut.setEntity(httpBody == null ? null : new StringEntity(httpBody, "UTF-8"));
httpRequest = httpPut;
break;
case DELETE:
httpRequest = new HttpDelete(safeUrl);
break;
default:
throw new IllegalArgumentException("Unrecognized HTTP method " + httpMethod);
}
// set request HTTP headers
for (HTTPHeader httpHeader : httpHeaders) {
httpRequest.setHeader(httpHeader.getName(), httpHeader.getValue());
}
// set HTTP basic auth
if (!"".equals(StringUtils.trimToEmpty(username))) {
String auth = username + ":" + password;
String encodedAuth = Base64.encodeBase64String(auth.getBytes());
String authHeader = "Basic " + encodedAuth;
httpRequest.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
final HTTPAPIResponse apiResponse = new HTTPAPIResponse();
final AtomicReference<Date> responseReceivedTime = new AtomicReference<>();
ResponseHandler<Void> responseHandler = httpResponse -> {
responseReceivedTime.set(new Date());
apiResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
apiResponse.getHttpHeaders().add(new HTTPHeader("*Status-Line*", httpResponse.getStatusLine().toString()));
Header[] headers = httpResponse.getAllHeaders();
for (Header header : headers) {
apiResponse.getHttpHeaders().add(new HTTPHeader(header.getName(), header.getValue()));
}
HttpEntity entity = httpResponse.getEntity();
apiResponse.setHttpBody(entity != null ? EntityUtils.toString(entity) : null);
return null;
};
// build HTTP Client instance, trusting all SSL certificates, using system HTTP proxy if needed and exists
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial((TrustStrategy) (chain, authType) -> true).build();
HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(connectionFactory);
InetAddress urlHost = InetAddress.getByName(new URL(url).getHost());
if (!(urlHost.isLoopbackAddress() || urlHost.isSiteLocalAddress())) {
// only use system proxy for external address
Proxy systemHTTPProxy = getSystemHTTPProxy();
if (systemHTTPProxy != null) {
InetSocketAddress addr = (InetSocketAddress) systemHTTPProxy.address();
httpClientBuilder.setProxy(new HttpHost(addr.getHostName(), addr.getPort()));
}
}
HttpClient httpClient = httpClientBuilder.build();
// invoke the API
Date invocationStartTime = new Date();
try {
httpClient.execute(httpRequest, responseHandler);
} catch (ClientProtocolException e) {
throw new RuntimeException(e.getCause().getMessage(), e);
}
long responseTime = responseReceivedTime.get().getTime() - invocationStartTime.getTime();
apiResponse.setResponseTime(responseTime);
return apiResponse;
}
use of io.irontest.core.teststep.HTTPAPIResponse in project irontest by zheng-wang.
the class SSLTrustedExternalResolver method resolveViaHttp.
public StringReader resolveViaHttp(String url) throws Exception {
URI uri = new URI(url);
uri = uri.normalize();
HTTPAPIResponse response = IronTestUtils.invokeHTTPAPI(uri.toString(), null, null, HTTPMethod.GET, new ArrayList<>(), null);
return new StringReader(response.getHttpBody());
}
Aggregations