Example usage for org.apache.http.client ResponseHandler ResponseHandler

List of usage examples for org.apache.http.client ResponseHandler ResponseHandler

Introduction

In this page you can find the example usage for org.apache.http.client ResponseHandler ResponseHandler.

Prototype

ResponseHandler

Source Link

Usage

From source file:api.WebServiceCommand.java

@Override
public CommandStatus execute() {
    CommandStatus status = new CommandStatus();
    try {/*from  ww w  . j  a  v a 2 s.c  om*/
        switch (this.httpVerb) {
        case "POST":
            status = Request.Post(this.uri).version(this.version).useExpectContinue()
                    .connectTimeout(this.connectionTimeout).socketTimeout(this.socketTimeout)
                    .bodyString(this.postString, this.contentType).execute()
                    .handleResponse(new ResponseHandler<HTTPCommandStatus>() {
                        @Override
                        public HTTPCommandStatus handleResponse(HttpResponse hr)
                                throws ClientProtocolException, IOException {
                            HTTPCommandStatus cs = new HTTPCommandStatus();
                            StatusLine statusLine = hr.getStatusLine();
                            HttpEntity entity = hr.getEntity();
                            cs.setHttpCode(statusLine.getStatusCode());
                            cs.setEntity(entity);
                            cs.setStderr(statusLine.getReasonPhrase());
                            return cs;
                        }
                    });
        case "GET":
        default:
            status = Request.Get(this.uri).version(this.version).connectTimeout(this.connectionTimeout)
                    .socketTimeout(this.socketTimeout).execute()
                    .handleResponse(new ResponseHandler<HTTPCommandStatus>() {
                        @Override
                        public HTTPCommandStatus handleResponse(HttpResponse hr)
                                throws ClientProtocolException, IOException {
                            HTTPCommandStatus cs = new HTTPCommandStatus();
                            StatusLine statusLine = hr.getStatusLine();
                            HttpEntity entity = hr.getEntity();
                            cs.setHttpCode(statusLine.getStatusCode());
                            cs.setEntity(entity);
                            cs.setStderr(statusLine.getReasonPhrase());
                            return cs;
                        }
                    });
            break;
        }
        if (this.debug) {
            System.out.println("   CODE RETURNED: '" + status.getStatus() + "'.");
            System.out.println("CONTOUT RETURNED: '" + status.getStdout() + "'.");
            System.out.println("CONTERR RETURNED: '" + status.getStderr() + "'.");
        }
    } catch (ClientProtocolException ex) {
        status.setEnded(ResponseTypes.CONFIG_ERROR.ordinal());
        System.out.println(ex.getMessage());
    } catch (IOException ex) {
        status.setEnded(ResponseTypes.FAIL.ordinal());
        System.out.println(ex.getMessage());
    }
    return status;
}

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

public String doGet(String url, Map<String, String> params) throws Exception {
    RequestBuilder _request = RequestBuilder.get().setUri(url);
    for (Map.Entry<String, String> entry : params.entrySet()) {
        _request.addParameter(entry.getKey(), entry.getValue());
    }// w ww.  ja va  2s.  c  om
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {
        _LOG.debug("Request URL [" + url + "], Param [" + params + "]");
        String _result = _httpClient.execute(_request.build(), new ResponseHandler<String>() {

            public String handleResponse(HttpResponse response) throws IOException {
                return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
            }

        });
        _LOG.debug("Request URL [" + url + "] Response [" + _result + "]");
        return _result;
    } finally {
        _httpClient.close();
    }
}

From source file:org.obm.sync.push.client.WBXMLOPClient.java

@Override
public <T> Future<T> postASyncXml(Async async, String namespace, Document doc, String cmd, String policyKey,
        boolean multipart, final ResponseTransformer<T> responseTransformer)
        throws TransformerException, WBXmlException, IOException, HttpRequestException {

    DOMUtils.logDom(doc);//from  w w  w. ja  va 2 s .  c  o  m

    Request request = buildRequest(namespace, doc, cmd, policyKey, multipart);

    return async.execute(request, new ResponseHandler<T>() {
        @Override
        public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            Document document = new DocumentResponseHandler().handleResponse(response);
            return responseTransformer.parse(document);
        }
    });
}

From source file:com.puppetlabs.geppetto.forge.client.ForgeHttpClient.java

private void doDownload(String urlStr, Map<String, String> params, final OutputStream output)
        throws IOException {
    HttpGet request = createGetRequest(urlStr, params);
    configureRequest(request);//  ww  w .  j  a v  a 2 s.c o  m
    httpClient.execute(request, new ResponseHandler<Void>() {
        @Override
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            int code = statusLine.getStatusCode();
            if (code != HttpStatus.SC_OK)
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());

            HttpEntity entity = response.getEntity();
            entity.writeTo(output);
            return null;
        }
    });
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void testTargetHost() throws Exception {
    HttpContext localContext = new BasicHttpContext();
    responses.add(new BasicHttpResponse(_200));
    client.execute(new HttpGet("http://example.com/200"), new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            return null;
        }/*  w  ww. j a  v  a2 s.c o m*/
    }, localContext);
    HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    assertEquals(ORIGIN, host.toString());
}

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ACIResultUploader.java

/**
 * {@inheritDoc}//from w w  w. ja  v a  2 s  . c  o m
 */
@Override
public void commit(final EnricherJob job) throws Exception {
    HttpPost httpPost = new HttpPost(new URI(commitUri));
    httpPost.setHeader(HEADER_USER_AGENT, userAgent);

    HttpResponse response = httpClient.execute(httpPost, new ResponseHandler<HttpResponse>() {
        @Override
        public HttpResponse handleResponse(final HttpResponse response)
                throws ClientProtocolException, IOException {
            return response;
        }
    });

    if (response.getStatusLine().getStatusCode() != HTTP_STATUS_SUCCESS)
        throw new Exception("Generated result could not be committed because of status "
                + response.getStatusLine().getStatusCode() + " (" + response.getStatusLine().getReasonPhrase()
                + ")");
    else if (logger.isDebugEnabled())
        logger.debug("Results have been committed to the indexer");
}

From source file:biocode.fims.ezid.EzidService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EzidService,
 * and so subsequent calls using this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 *
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 *
 * @throws EzidException if authentication fails for any reason
 *///from   w w  w.  j  a v a  2 s.  c  o  m
public void login(String username, String password) throws EzidException {
    String msg;
    try {
        URI serviceUri = new URI(LOGIN_SERVICE);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        //System.out.println("authCache: " + authCache.toString());

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(LOGIN_SERVICE);
        body = httpClient.execute(httpget, handler, localcontext);
        String message = new String(body);
        msg = parseIdentifierResponse(message);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        /*
                org.apache.http.client.CookieStore cookieStore = httpClient.getCookieStore();
        System.out.println("\n\nCookies : ");
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Cookie: " + cookies.get(i));
        } */

    } catch (URISyntaxException e) {
        //System.out.println("URI SyntaxError Exception in LOGIN");
        throw new EzidException("Bad syntax for uri: " + LOGIN_SERVICE, e);
    } catch (ClientProtocolException e) {
        //System.out.println("ClientProtocol Exception in LOGIN");
        throw new EzidException(e);
    } catch (IOException e) {
        //System.out.println("IO Exception in LOGIN");
        throw new EzidException(e);
    }
    //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString());
}

From source file:org.commonjava.web.json.test.WebFixture.java

public <T> T get(final String url, final Class<T> type) throws Exception {
    logger.info("WebFixture: GET '{}', expecting: 200, return-type: {}", url, type.getName());
    final HttpGet get = new HttpGet(url);
    get.setHeader(HttpHeaders.ACCEPT, "application/json");
    try {//from   w  ww  .  j  a v a 2 s. c  o m
        return http.execute(get, new ResponseHandler<T>() {
            @Override
            public T handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                final StatusLine sl = response.getStatusLine();
                assertThat(sl.getStatusCode(), equalTo(HttpStatus.SC_OK));

                return serializer.fromStream(response.getEntity().getContent(), "UTF-8", type);
            }
        });
    } finally {
        get.abort();
    }
}

From source file:org.eclipse.californium.proxy.resources.ProxyHttpClientResource.java

@Override
public Response forwardRequest(Request request) {
    final Request incomingCoapRequest = request;

    // check the invariant: the request must have the proxy-uri set
    if (!incomingCoapRequest.getOptions().hasProxyUri()) {
        LOGGER.warning("Proxy-uri option not set.");
        return new Response(ResponseCode.BAD_OPTION);
    }/*from  w w w.j  av  a  2 s  .  co m*/

    // remove the fake uri-path // TODO: why? still necessary in new Cf?
    incomingCoapRequest.getOptions().clearUriPath();
    ; // HACK

    // get the proxy-uri set in the incoming coap request
    URI proxyUri;
    try {
        String proxyUriString = URLDecoder.decode(incomingCoapRequest.getOptions().getProxyUri(), "UTF-8");
        proxyUri = new URI(proxyUriString);
    } catch (UnsupportedEncodingException e) {
        LOGGER.warning("Proxy-uri option malformed: " + e.getMessage());
        return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
    } catch (URISyntaxException e) {
        LOGGER.warning("Proxy-uri option malformed: " + e.getMessage());
        return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
    }

    // get the requested host, if the port is not specified, the constructor
    // sets it to -1
    HttpHost httpHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme());

    HttpRequest httpRequest = null;
    try {
        // get the mapping to http for the incoming coap request
        httpRequest = HttpTranslator.getHttpRequest(incomingCoapRequest);
        LOGGER.finer("Outgoing http request: " + httpRequest.getRequestLine());
    } catch (InvalidFieldException e) {
        LOGGER.warning("Problems during the http/coap translation: " + e.getMessage());
        return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
    } catch (TranslationException e) {
        LOGGER.warning("Problems during the http/coap translation: " + e.getMessage());
        return new Response(CoapTranslator.STATUS_TRANSLATION_ERROR);
    }

    ResponseHandler<Response> httpResponseHandler = new ResponseHandler<Response>() {
        @Override
        public Response handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            long timestamp = System.nanoTime();
            LOGGER.finer("Incoming http response: " + httpResponse.getStatusLine());
            // the entity of the response, if non repeatable, could be
            // consumed only one time, so do not debug it!
            // System.out.println(EntityUtils.toString(httpResponse.getEntity()));

            // translate the received http response in a coap response
            try {
                Response coapResponse = HttpTranslator.getCoapResponse(httpResponse, incomingCoapRequest);
                coapResponse.setTimestamp(timestamp);
                return coapResponse;
            } catch (InvalidFieldException e) {
                LOGGER.warning("Problems during the http/coap translation: " + e.getMessage());
                return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
            } catch (TranslationException e) {
                LOGGER.warning("Problems during the http/coap translation: " + e.getMessage());
                return new Response(CoapTranslator.STATUS_TRANSLATION_ERROR);
            }
        }
    };

    // accept the request sending a separate response to avoid the timeout
    // in the requesting client
    LOGGER.finer("Acknowledge message sent");

    Response coapResponse = null;
    try {
        // execute the request
        coapResponse = HTTP_CLIENT.execute(httpHost, httpRequest, httpResponseHandler, null);
    } catch (IOException e) {
        LOGGER.warning("Failed to get the http response: " + e.getMessage());
        return new Response(ResponseCode.INTERNAL_SERVER_ERROR);
    }

    return coapResponse;
}

From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java

protected void testHttpClientWithResponseHandler(HttpUriRequest request, boolean fault) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  w  w w  .  j a v a  2s  .  com
        request.addHeader("test-header", "test-value");
        if (fault) {
            request.addHeader("test-fault", "true");
        }

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();

                assertEquals("Unexpected response code", 200, status);

                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }

        };

        String responseBody = httpclient.execute(request, responseHandler);

        assertEquals(HELLO_WORLD, responseBody);

    } catch (ConnectException ce) {
        assertEquals(BAD_URL, request.getURI().toString());
    } finally {
        httpclient.close();
    }

    Wait.until(() -> getTracer().finishedSpans().size() == 1);

    List<MockSpan> spans = getTracer().finishedSpans();
    assertEquals(1, spans.size());
    assertEquals(Tags.SPAN_KIND_CLIENT, spans.get(0).tags().get(Tags.SPAN_KIND.getKey()));
    assertEquals(request.getMethod(), spans.get(0).operationName());
    assertEquals(request.getURI().toString(), spans.get(0).tags().get(Tags.HTTP_URL.getKey()));
    if (fault) {
        assertEquals("401", spans.get(0).tags().get(Tags.HTTP_STATUS.getKey()));
    }
}