use of org.apache.http.client.ResponseHandler in project openhab1-addons by openhab.
the class StreamClientImpl method createResponseHandler.
protected ResponseHandler<StreamResponseMessage> createResponseHandler() {
return new ResponseHandler<StreamResponseMessage>() {
@Override
public StreamResponseMessage handleResponse(final HttpResponse httpResponse) throws IOException {
StatusLine statusLine = httpResponse.getStatusLine();
log.fine("Received HTTP response: " + statusLine);
// Status
UpnpResponse responseOperation = new UpnpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase());
// Message
StreamResponseMessage responseMessage = new StreamResponseMessage(responseOperation);
// Headers
responseMessage.setHeaders(new UpnpHeaders(HeaderUtil.get(httpResponse)));
// Body
HttpEntity entity = httpResponse.getEntity();
if (entity == null || entity.getContentLength() == 0) {
return responseMessage;
}
if (responseMessage.isContentTypeMissingOrText()) {
log.fine("HTTP response message contains text entity");
responseMessage.setBody(UpnpMessage.BodyType.STRING, EntityUtils.toString(entity));
} else {
log.fine("HTTP response message contains binary entity");
responseMessage.setBody(UpnpMessage.BodyType.BYTES, EntityUtils.toByteArray(entity));
}
return responseMessage;
}
};
}
use of org.apache.http.client.ResponseHandler in project ribbon by Netflix.
the class NFHttpClientTest method testNFHttpClient.
@Test
public void testNFHttpClient() throws Exception {
NFHttpClient client = NFHttpClientFactory.getNFHttpClient("localhost", server.getServerPort());
ThreadSafeClientConnManager cm = (ThreadSafeClientConnManager) client.getConnectionManager();
cm.setDefaultMaxPerRoute(10);
HttpGet get = new HttpGet(server.getServerURI());
ResponseHandler<Integer> respHandler = new ResponseHandler<Integer>() {
public Integer handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
String contentStr = EntityUtils.toString(entity);
return contentStr.length();
}
};
long contentLen = client.execute(get, respHandler);
assertTrue(contentLen > 0);
}
use of org.apache.http.client.ResponseHandler in project LiveSDK-for-Android by liveservices.
the class UploadRequestTest method testSendPathQueryParameterToHttpPut.
/**
* WinLive 633441: Make sure the query parameters on path get sent to
* the HTTP PUT part of the upload.
*/
public void testSendPathQueryParameterToHttpPut() throws Throwable {
JSONObject jsonResponseBody = new JSONObject();
jsonResponseBody.put(JsonKeys.UPLOAD_LOCATION, "http://test.com/location");
InputStream responseStream = new ByteArrayInputStream(jsonResponseBody.toString().getBytes());
MockHttpEntity responseEntity = new MockHttpEntity(responseStream);
BasicStatusLine ok = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "");
final MockHttpResponse uploadLocationResponse = new MockHttpResponse(responseEntity, ok);
HttpClient client = new HttpClient() {
/** the first request to the client is the upload location request. */
boolean uploadLocationRequest = true;
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException {
if (uploadLocationRequest) {
uploadLocationRequest = false;
return uploadLocationResponse;
}
// This is really the only part we care about in this test.
// That the 2nd request's uri has foo=bar in the query string.
URI uri = request.getURI();
assertEquals("foo=bar&overwrite=choosenewname", uri.getQuery());
// just return the previous reponse.
return uploadLocationResponse;
}
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1, HttpContext arg2) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpHost arg0, HttpRequest arg1, ResponseHandler<? extends T> arg2) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpHost arg0, HttpRequest arg1, ResponseHandler<? extends T> arg2, HttpContext arg3) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public ClientConnectionManager getConnectionManager() {
throw new UnsupportedOperationException();
}
@Override
public HttpParams getParams() {
throw new UnsupportedOperationException();
}
};
LiveConnectSession session = TestUtils.newMockLiveConnectSession();
HttpEntity entity = new MockHttpEntity();
String path = Paths.ME_SKYDRIVE + "?foo=bar";
String filename = "filename";
UploadRequest uploadRequest = new UploadRequest(session, client, path, entity, filename, OverwriteOption.Rename);
uploadRequest.execute();
}
use of org.apache.http.client.ResponseHandler in project ats-framework by Axway.
the class HttpClient method execute.
/**
* Main execute method that sends request and receives response.
*
* @param method The POST/PUT etc. method
* @return The response
* @throws HttpException
*/
private HttpResponse execute(HttpRequestBase httpMethod) throws HttpException {
HttpClientContext localContext = null;
if (httpClient == null) {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
// Add this interceptor to get the values of all HTTP headers in the request.
// Some of them are provided by the user while others are generated by Apache HTTP Components.
httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
Header[] requestHeaders = request.getAllHeaders();
actualRequestHeaders = new ArrayList<HttpHeader>();
for (Header header : requestHeaders) {
addHeaderToList(actualRequestHeaders, header.getName(), header.getValue());
}
if (debugLevel != HttpDebugLevel.NONE) {
logHTTPRequest(requestHeaders, request);
}
}
});
// Setup authentication
if (!StringUtils.isNullOrEmpty(username)) {
localContext = setupAuthentication(httpClientBuilder);
}
// Setup SSL
if (url.toLowerCase().startsWith("https")) {
setupSSL(httpClientBuilder);
}
// all important options are set, now build the HTTP client
if (AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST != null && AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT != null) {
HttpHost proxy = new HttpHost(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST, Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClient = httpClientBuilder.setRoutePlanner(routePlanner).build();
} else {
httpClient = httpClientBuilder.build();
}
}
// Setup read and connect timeouts
httpMethod.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutSeconds * 1000).setConnectTimeout(connectTimeoutSeconds * 1000).build());
// Add HTTP headers
addHeadersToHttpMethod(httpMethod);
// Create response handler
ResponseHandler<HttpResponse> responseHandler = new ResponseHandler<HttpResponse>() {
@Override
public HttpResponse handleResponse(final org.apache.http.HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
Header[] responseHeaders = response.getAllHeaders();
List<HttpHeader> responseHeadersList = new ArrayList<HttpHeader>();
for (Header header : responseHeaders) {
addHeaderToList(responseHeadersList, header.getName(), header.getValue());
}
if ((debugLevel & HttpDebugLevel.HEADERS) == HttpDebugLevel.HEADERS) {
logHTTPResponse(responseHeaders, response);
}
try {
HttpEntity entity = response.getEntity();
if (entity == null) {
// No response body, generally have '204 No content' status
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
} else {
if (responseBodyFilePath != null) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(responseBodyFilePath), false);
entity.writeTo(fos);
} finally {
IoUtils.closeStream(fos);
}
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
entity.writeTo(bos);
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList, bos.toByteArray());
}
}
} finally {
if (response instanceof CloseableHttpResponse) {
IoUtils.closeStream((CloseableHttpResponse) response, "Failed to close HttpResponse");
}
}
}
};
// Send the request as POST/GET etc. and return response.
try {
return httpClient.execute(httpMethod, responseHandler, localContext);
} catch (IOException e) {
throw new HttpException("Exception occurred sending message to URL '" + actualUrl + "' with a read timeout of " + readTimeoutSeconds + " seconds and a connect timeout of " + connectTimeoutSeconds + " seconds.", e);
} finally {
// clear internal variables
ActionLibraryConfigurator actionLibraryConfigurator = ActionLibraryConfigurator.getInstance();
if (!actionLibraryConfigurator.getHttpKeepRequestHeaders()) {
this.requestHeaders.clear();
}
if (!actionLibraryConfigurator.getHttpKeepRequestParameters()) {
this.requestParameters.clear();
}
if (!actionLibraryConfigurator.getHttpKeepRequestBody()) {
this.requestBody = null;
}
this.responseBodyFilePath = null;
}
}
use of org.apache.http.client.ResponseHandler in project voltdb by VoltDB.
the class TestJSONInterface method httpUrlOverJSONExecute.
private static String httpUrlOverJSONExecute(String method, String url, String user, String password, String scheme, int expectedCode, String expectedCt, String varString) throws Exception {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true).build();
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
// allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClientBuilder hb = HttpClientBuilder.create();
hb.setSslcontext(sslContext);
hb.setConnectionManager(connMgr);
try (CloseableHttpClient httpclient = hb.build()) {
HttpRequestBase request;
switch(method) {
case "POST":
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
request = post;
break;
case "PUT":
HttpPut put = new HttpPut(url);
put.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
request = put;
break;
case "DELETE":
HttpDelete delete = new HttpDelete(url);
request = delete;
break;
case "GET":
request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
break;
default:
request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
break;
}
// play nice by using HTTP 1.1 continue requests where the client sends the request headers first
// to the server to see if the server is willing to accept it. This allows us to test large requests
// without incurring server socket connection terminations
RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
request.setProtocolVersion(HttpVersion.HTTP_1_1);
request.setConfig(rc);
if (user != null && password != null) {
if (scheme.equalsIgnoreCase("hashed")) {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
request.setHeader("Authorization", "Hashed " + h);
} else if (scheme.equalsIgnoreCase("hashed256")) {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
request.setHeader("Authorization", "Hashed " + h);
} else if (scheme.equalsIgnoreCase("basic")) {
request.setHeader("Authorization", "Basic " + new String(Base64.encodeToString(new String(user + ":" + password).getBytes(), false)));
}
}
ResponseHandler<String> rh = new ResponseHandler<String>() {
@Override
public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
String ct = response.getHeaders("Content-Type")[0].getValue();
if (expectedCt != null) {
assertTrue(ct.contains(expectedCt));
}
assertEquals(expectedCode, status);
if ((status >= 200 && status < 300) || HANDLED_CLIENT_ERRORS.contains(status)) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return null;
}
};
return httpclient.execute(request, rh);
}
}
Aggregations