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:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 *
 * @param msgContext/*  w  ww  . ja v a2 s .  c o m*/
 *            the messsage context
 *
 * @throws AxisFault
 */
public void invoke(final MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    Request req = null;
    Response response = null;
    try {
        if (exec == null) {
            targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
            String userID = msgContext.getUsername();
            String passwd = msgContext.getPassword();
            // if UserID is not part of the context, but is in the URL, use
            // the one in the URL.
            if ((userID == null) && (targetURL.getUserInfo() != null)) {
                String info = targetURL.getUserInfo();
                int sep = info.indexOf(':');

                if ((sep >= 0) && (sep + 1 < info.length())) {
                    userID = info.substring(0, sep);
                    passwd = info.substring(sep + 1);
                } else
                    userID = info;
            }
            Credentials cred = new UsernamePasswordCredentials(userID, passwd);
            if (userID != null) {
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = userID.indexOf("\\");
                if (domainIndex > 0) {
                    String domain = userID.substring(0, domainIndex);
                    if (userID.length() > domainIndex + 1) {
                        String user = userID.substring(domainIndex + 1);
                        cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
                    }
                }
            }
            HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() {

                public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                        final HttpContext context) throws ProtocolException {
                    URI uri = getLocationURI(request, response, context);
                    String method = request.getRequestLine().getMethod();
                    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME))
                        return new HttpHead(uri);
                    else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                        HttpPost httpPost = new HttpPost(uri);
                        httpPost.addHeader(request.getFirstHeader("Authorization"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        httpPost.addHeader(request.getFirstHeader("Content-Type"));
                        httpPost.addHeader(request.getFirstHeader("User-Agent"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        if (request instanceof HttpEntityEnclosingRequest)
                            httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
                        return httpPost;
                    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
                        return new HttpGet(uri);
                    } else {
                        throw new IllegalStateException(
                                "Redirect called on un-redirectable http method: " + method);
                    }
                }
            }).build();

            exec = Executor.newInstance(httpClient);
            HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol());
            exec.auth(host, cred);
            exec.authPreemptive(host);
            HttpUtils.setupProxy(exec, targetURL.toURI());
        }
        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
        HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI());
        if (posting) {
            req = Request.Post(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            Message reqMessage = msgContext.getRequestMessage();

            addContextInfo(req, msgContext, targetURL);
            Iterator<?> it = reqMessage.getAttachments();
            if (it.hasNext()) {
                ByteArrayOutputStream bos = null;
                try {
                    bos = new ByteArrayOutputStream();
                    reqMessage.writeTo(bos);
                    req.body(new ByteArrayEntity(bos.toByteArray()));
                } finally {
                    FileUtils.closeStream(bos);
                }
            } else
                req.body(new StringEntity(reqMessage.getSOAPPartAsString()));

        } else {
            req = Request.Get(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            addContextInfo(req, msgContext, targetURL);
        }

        response = exec.execute(req);
        response.handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity en = response.getEntity();
                InputStream in = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    int returnCode = statusLine.getStatusCode();
                    String contentType = en.getContentType().getValue();

                    in = new BufferedHttpEntity(en).getContent();
                    // String str = IOUtils.toString(in);
                    if (returnCode > 199 && returnCode < 300) {
                        // SOAP return is OK - so fall through
                    } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
                        // For now, if we're SOAP 1.2, fall
                        // through, since the range of
                        // valid result codes is much greater
                    } else if (contentType != null && !contentType.equals("text/html")
                            && ((returnCode > 499) && (returnCode < 600))) {
                        // SOAP Fault should be in here - so
                        // fall through
                    } else {
                        String statusMessage = statusLine.getReasonPhrase();
                        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null,
                                null);
                        fault.setFaultDetailString(
                                Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in)));
                        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
                                Integer.toString(returnCode));
                        throw fault;
                    }
                    Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP))
                            in = new GZIPInputStream(in);
                        else {
                            AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '"
                                    + contentEncoding.getValue() + "' found", null, null);
                            throw fault;
                        }

                    }

                    // Transfer HTTP headers of HTTP message
                    // to MIME headers of SOAP
                    // message
                    MimeHeaders mh = new MimeHeaders();
                    for (Header h : response.getAllHeaders())
                        mh.addHeader(h.getName(), h.getValue());
                    Message outMsg = new Message(in, false, mh);

                    outMsg.setMessageType(Message.RESPONSE);
                    msgContext.setResponseMessage(outMsg);
                    if (log.isDebugEnabled()) {
                        log.debug("\n" + Messages.getMessage("xmlRecd00"));
                        log.debug("-----------------------------------------------");
                        log.debug(outMsg.getSOAPPartAsString());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return "";
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        log.debug(e);
        throw AxisFault.makeFault(e);
    }
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
}

From source file:org.apache.marmotta.platform.core.services.content.HTTPContentReader.java

/**
 * Return the MIME content type of the resource passed as argument.
 *
 * @param resource resource for which to return the content type
 * @return the MIME content type of the resource
 *//*  w  ww.ja  v  a 2 s .c  o  m*/
@Override
public String getContentType(Resource resource) {
    try {
        RepositoryConnection conn = sesameService.getConnection();
        try {
            MediaContentItem mci = FacadingFactory.createFacading(conn).createFacade(resource,
                    MediaContentItem.class);

            String location = mci.getContentLocation();

            // if no location is explicitly specified, use the resource URI itself
            if (location == null && resource instanceof URI && resource.stringValue().startsWith("http://")) {
                location = resource.stringValue();
            }

            try {
                if (location != null) {
                    log.info("reading remote resource {}", location);
                    HttpHead head = new HttpHead(location);

                    return httpClientService.execute(head, new ResponseHandler<String>() {
                        @Override
                        public String handleResponse(HttpResponse response)
                                throws ClientProtocolException, IOException {
                            if (response.getStatusLine().getStatusCode() == 200)
                                return response.getFirstHeader("Content-Type").getValue().split(";")[0];
                            else
                                return null;
                        }
                    });
                } else
                    return null;
            } catch (IOException ex) {
                return null;
            }
        } finally {
            conn.commit();
            conn.close();
        }
    } catch (RepositoryException ex) {
        handleRepositoryException(ex, FileSystemContentReader.class);
        return null;
    }
}

From source file:net.ymate.framework.commons.HttpClientHelper.java

public IHttpResponse post(String url, ContentType contentType, String content, Header[] headers,
        final String defaultResponseCharset) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {//from ww  w  . j a va 2s . c  o  m
        RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create()
                .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET
                        : contentType.getCharset().name())
                .setContentType(contentType).setText(content).build());
        if (headers != null && headers.length > 0) {
            for (Header _header : headers) {
                _reqBuilder.addHeader(_header);
            }
        }
        return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() {

            public IHttpResponse handleResponse(HttpResponse response) throws IOException {
                if (StringUtils.isNotBlank(defaultResponseCharset)) {
                    return new IHttpResponse.NEW(response, defaultResponseCharset);
                }
                return new IHttpResponse.NEW(response);
            }

        });
    } finally {
        _httpClient.close();
    }
}

From source file:net.adamcin.granite.client.packman.http4.Http4PackageManagerClient.java

private DetailedResponse executeDetailedRequest(final HttpUriRequest request,
        final ResponseProgressListener listener) throws Exception {
    return getClient().execute(request, new ResponseHandler<DetailedResponse>() {
        public DetailedResponse handleResponse(final HttpResponse response)
                throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            return parseDetailedResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(),
                    response.getEntity().getContent(), getResponseEncoding(response), listener);
        }/*from  w w w .j a  va  2  s . co m*/
    }, getHttpContext());
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

private static String readData(Executor exec, Request req, IProgressMonitor monitor) throws IOException {
    String obj = null;//  w w  w. ja  va2  s. c  om
    ConnectionManager.register(monitor, req);
    try {
        obj = exec.execute(req).handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity entity = response.getEntity();
                InputStream in = null;
                String res = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    // System.out
                    // .println("---------------------------------------------------------------------------");
                    // System.out.println(response.toString());
                    // for (Header h : response.getAllHeaders()) {
                    // System.out.println(h.toString());
                    // }

                    switch (statusLine.getStatusCode()) {
                    case 200:
                        in = getContent(entity);
                        res = IOUtils.toString(in);
                        break;
                    default:
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return res;
            }

            protected InputStream getContent(HttpEntity entity) throws ClientProtocolException, IOException {
                if (entity == null)
                    throw new ClientProtocolException("Response contains no content");
                return entity.getContent();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        ConnectionManager.unregister(req);
    }
    return obj;
}

From source file:com.networknt.validator.ValidatorHandlerTest.java

@Test
public void testInvalidMethod() throws Exception {
    String url = "http://localhost:8080/v2/pet";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override/*from   ww w  .ja  v a2  s  .  c  o m*/
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            Assert.assertEquals(405, status);
            return null;
        }
    };
    String responseBody = null;
    try {
        responseBody = client.execute(httpGet, responseHandler);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.commonjava.aprox.client.core.AproxClientHttp.java

public void putWithStream(final String path, final InputStream stream, final int... responseCodes)
        throws AproxClientException {
    connect();//www. j  a  v  a  2 s. c om

    final HttpPut put = newRawPut(buildUrl(baseUrl, path));
    final CloseableHttpClient client = newClient();
    try {
        put.setEntity(new InputStreamEntity(stream));

        client.execute(put, new ResponseHandler<Void>() {
            @Override
            public Void handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                try {
                    final StatusLine sl = response.getStatusLine();
                    if (!validResponseCode(sl.getStatusCode(), responseCodes)) {
                        throw new ClientProtocolException(
                                String.format("Error in response from: %s. Status was: %d %s (%s)", path,
                                        sl.getStatusCode(), sl.getReasonPhrase(), sl.getProtocolVersion()));
                    }

                    return null;
                } finally {
                    cleanupResources(put, response, client);
                }
            }
        });

    } catch (final IOException e) {
        throw new AproxClientException("AProx request failed: %s", e, e.getMessage());
    }
}

From source file:org.teleal.cling.transport.impl.apache.StreamClientImpl.java

protected ResponseHandler<StreamResponseMessage> createResponseHandler() {
    return new ResponseHandler<StreamResponseMessage>() {
        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));
            }//from   w  ww. j a v  a 2s  .co m

            return responseMessage;
        }
    };
}

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

@Test
public void test302CachedRedirectTarget() throws Exception {
    do {/*  w w w .  ja v  a2s  .c o  m*/
        HttpGet get = new HttpGet("http://example.com/302");
        get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        BasicHttpResponse redirect = new BasicHttpResponse(_302);
        redirect.setHeader("Location", "http://example.com/200");
        redirect.setHeader("Cache-Control", "public,max-age=3600");
        responses.add(redirect);
        BasicHttpResponse doc = new BasicHttpResponse(_200);
        doc.setHeader("Cache-Control", "public,max-age=3600");
        responses.add(doc);
        client.execute(get, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
                return null;
            }
        });
    } while (false);
    do {
        HttpContext localContext = new BasicHttpContext();
        HttpGet get = new HttpGet("http://example.com/302");
        get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        BasicHttpResponse redirect = new BasicHttpResponse(_302);
        redirect.setHeader("Location", "http://example.com/200");
        redirect.setHeader("Cache-Control", "public,max-age=3600");
        responses.add(redirect);
        client.execute(get, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertEquals(_302.getStatusCode(), response.getStatusLine().getStatusCode());
                return null;
            }
        }, localContext);
        HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        URI root = new URI(host.getSchemeName(), null, host.getHostName(), -1, "/", null, null);
        assertEquals("http://example.com/302", root.resolve(req.getURI()).toASCIIString());
    } while (false);
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

/**
 * /*from www.  j a  v  a  2s  .c o  m*/
 * 
 * @throws Exception
 */
@Test
public void testResponseHandler() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL1);
    HttpContext context = new BasicHttpContext();

    httpGet.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    System.out.println("Go Aready...");

    HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {

        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            System.out.println("---------------------------------------");

            System.out.println("Request encoding... "
                    + request.getParams().getParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET));
        }
    };

    HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {

        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            System.out.println("---------------------------------------");

            System.out.println("Response encoding... "
                    + response.getParams().getParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET));

        }
    };

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                Header[] allHeaders = response.getAllHeaders();
                if (allHeaders.length > 0) {
                    for (Header header : allHeaders) {
                        String name = header.getName();
                        String value = header.getValue();
                        System.out.println(name + " = " + value);
                    }
                    System.out.println("-----------------------------------");
                }

                String charset = "UTF-8";
                HttpEntity entity = response.getEntity();
                Header encoding = entity.getContentEncoding();
                if (encoding != null) {
                    charset = encoding.getValue();
                }
                System.out.println("charset ==>" + charset);

                if (entity != null) {
                    InputStream in = entity.getContent();
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    IOUtils.copy(in, out);

                    byte[] bytes = out.toByteArray();
                    if (bytes.length > 0) {
                        String content = new String(bytes, charset);
                        return content;
                    }
                }
                return null;

            } else {
                return statusCode + " | " + statusLine.getReasonPhrase();
            }
        }
    };

    httpclient.addRequestInterceptor(requestInterceptor);
    httpclient.addResponseInterceptor(responseInterceptor);
    String content = httpclient.execute(httpGet, responseHandler, context);

    System.out.println(content);
}