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.partnet.automation.http.ApacheHttpAdapter.java

private Response method(HttpRequestBase httpRequestBase, String contentType, String body) {
    Response.Builder responseBuilder;

    if (httpRequestBase instanceof HttpEntityEnclosingRequestBase) {
        this.setEntity((HttpEntityEnclosingRequestBase) httpRequestBase, contentType, body);
    }/*w w w.  j  a  va 2 s  .com*/

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        LOG.debug("Executing request " + httpRequestBase.getRequestLine());

        if (httpRequestBase instanceof HttpEntityEnclosingRequestBase) {
            HttpEntity entity = (((HttpEntityEnclosingRequestBase) httpRequestBase).getEntity());
            if (entity != null) {
                LOG.debug("Body being sent: " + EntityUtils.toString(entity));
            }
        }

        //handle response
        ResponseHandler<Response.Builder> responseHandler = new ResponseHandler<Response.Builder>() {

            @Override
            public Response.Builder handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                Response.Builder rb = new Response.Builder();

                if (response.getEntity() != null) {
                    rb.setBody(EntityUtils.toString(response.getEntity()));
                }

                rb.setStatusCode(response.getStatusLine().getStatusCode());
                rb.setHeaders(convertApacheToHeaderAdapter(response.getAllHeaders()));

                if (response.getEntity() != null) {
                    rb.setContentType(convertApacheToHeaderAdapter(response.getEntity().getContentType())[0]);
                }

                return rb;
            }
        };

        //handle cookies
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        responseBuilder = httpclient.execute(httpRequestBase, responseHandler, context);

        responseBuilder.setCookies(convertCookieToAdapter(context.getCookieStore().getCookies()));

    } catch (IOException e) {
        throw new IllegalStateException("IOException occurred while attempting to communicate with endpoint",
                e);
    }
    return responseBuilder.build();
}

From source file:org.skfiy.typhon.spi.auth.p.UCRoleListener.java

@Override
public void roleCreated(Role role) {
    Object p = SessionContext.getSession().getAttribute(UCAuthenticator.SESSION_SID_KEY);
    if (p == null) {
        return;//  w w  w . jav  a2  s. co m
    }

    CloseableHttpClient hc = UCAuthenticator.HC_BUILDER.build();
    HttpPost httpPost = new HttpPost("http://sdk.g.uc.cn/cp/account.verifySession");

    JSONObject json = new JSONObject();
    json.put("id", System.currentTimeMillis());
    json.put("service", "ucid.game.gameData");

    String sid = (String) p;
    String gameData = getGameData();

    JSONObject data = new JSONObject();
    data.put("sid", sid);
    data.put("gameData", gameData);
    json.put("data", data);

    JSONObject game = new JSONObject();
    game.put("gameId", UCAuthenticator.gameId);
    json.put("game", game);

    json.put("sign", getSign(gameData, sid));

    try {
        String body = json.toJSONString();
        LOG.debug("UC loginGameRole request: {}", body);

        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new ByteArrayEntity(body.getBytes("UTF-8")));
        hc.execute(httpPost, new ResponseHandler<JSONObject>() {

            @Override
            public JSONObject handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                String str = StreamUtils.copyToString(response.getEntity().getContent(),
                        StandardCharsets.UTF_8);
                LOG.debug("UC loginGameRole response: {}", str);
                return JSON.parseObject(str);
            }
        });
    } catch (IOException e) {
        throw new OAuth2Exception("UC??", e);
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }
}

From source file:org.commonjava.util.jhttpc.unit.HttpFactoryTest.java

@Test
public void simpleSingleGet_NoSiteConfig() throws Exception {
    String path = "/path/to/test";
    String content = "This is a test.";

    server.expect(server.formatUrl(path), 200, content);

    HttpFactory factory = new HttpFactory(new MemoryPasswordManager());
    CloseableHttpClient client = null;/*from  w  w w.  j a v a2  s.c  o m*/
    try {
        client = factory.createClient();
        String result = client.execute(new HttpGet(server.formatUrl(path)), new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
                return IOUtils.toString(response.getEntity().getContent());
            }
        });

        assertThat(result, equalTo(content));
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:ranktracker.crawler.google.SeoKeywordDetail.java

public static String fetchSemrushPage(String urlsrc) throws IOException {
    System.out.println("---------------Without Proxy-----------------");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String responseBody = "";
    try {/*  w  w  w . jav a 2 s . com*/
        HttpGet httpget = new HttpGet(urlsrc);

        System.out.println("executing request " + httpget.getURI());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status <= 600) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        responseBody = httpclient.execute(httpget, responseHandler);
        return responseBody;
    } catch (Exception e) {
        System.out.println("Exception in getting the sourec code from website :" + e);
    } finally {
        try {
            httpclient.close();
        } catch (Exception e) {
            System.out.println("Exception " + e);
        }
    }

    return responseBody;
}

From source file:eu.eubrazilcc.lvl.storage.urlshortener.UrlShortener.java

private static final String loadShortenedUrl(final String url) throws Exception {
    String url2 = null, shortenedUrl = null;
    checkArgument(isNotBlank(url2 = trimToNull(url)), "Uninitialized or invalid url");
    try (final TrustedHttpsClient httpClient = new TrustedHttpsClient()) {
        final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                final int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    final HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }/*w  w w  .j a v a 2  s  .c  o m*/
            }
        };
        final String response = httpClient.executePost(
                URL_SHORTENER + (isNotBlank(CONFIG_MANAGER.getGoogleAPIKey())
                        ? "?key=" + urlEncodeUtf8(CONFIG_MANAGER.getGoogleAPIKey())
                        : ""),
                ImmutableMap.of("Accept", "application/json", "Content-type", "application/json"),
                new StringEntity("{ \"longUrl\" : \"" + url2 + "\" }"), responseHandler);
        final Map<String, String> map = JSON_MAPPER.readValue(response,
                new TypeReference<HashMap<String, String>>() {
                });
        checkState(map != null, "Server response is invalid");
        shortenedUrl = map.get("id");
        checkState(isNotBlank(shortenedUrl), "No shortened URL found in server response");
    }
    return shortenedUrl;
}

From source file:org.sikuli.script.App.java

/**
 * issue a http(s) request//from   w w  w.  j a v  a 2s. c  om
 * @param url a valid url as used in a browser
 * @return textual content of the response or empty (UTF-8)
 * @throws IOException
 */
public static String wwwGet(String url) throws IOException {
    HttpGet httpget = new HttpGet(url);
    CloseableHttpResponse response = null;
    ResponseHandler rh = new ResponseHandler() {
        @Override
        public String handleResponse(final HttpResponse response) throws IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response has no content");
            }
            InputStream is = entity.getContent();
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }
            return result.toString("UTF-8");
        }
    };
    boolean oneTime = false;
    if (httpclient == null) {
        wwwStart();
        oneTime = true;
    }
    Object content = httpclient.execute(httpget, rh);
    if (oneTime) {
        wwwStop();
    }
    return (String) content;
}

From source file:org.cerberus.service.rest.impl.RestService.java

private AppService executeHTTPCall(CloseableHttpClient httpclient, HttpRequestBase httpget) throws Exception {
    try {/* ww w. jav a  2  s . com*/
        // Create a custom response handler
        ResponseHandler<AppService> responseHandler = new ResponseHandler<AppService>() {

            @Override
            public AppService handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                AppService myResponse = factoryAppService.create("", AppService.TYPE_REST,
                        AppService.METHOD_HTTPGET, "", "", "", "", "", "", "", "", null, "", null);
                int responseCode = response.getStatusLine().getStatusCode();
                myResponse.setResponseHTTPCode(responseCode);
                myResponse.setResponseHTTPVersion(response.getProtocolVersion().toString());
                LOG.info(String.valueOf(responseCode) + " " + response.getProtocolVersion().toString());
                Header[] allHeaderList = response.getAllHeaders();
                for (Header header : allHeaderList) {
                    myResponse.addResponseHeaderList(factoryAppServiceHeader.create(null, header.getName(),
                            header.getValue(), "Y", 0, "", "", null, "", null));
                }
                HttpEntity entity = response.getEntity();
                myResponse.setResponseHTTPBody(entity != null ? EntityUtils.toString(entity) : null);
                return myResponse;
            }

        };
        return httpclient.execute(httpget, responseHandler);

    } catch (Exception ex) {
        LOG.error(ex.toString());
        throw ex;
    } finally {
        httpclient.close();
    }
}

From source file:org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl.java

/**
 * {@inheritDoc}//from   w w  w  .  j a v  a 2s  .c  om
 */
@Override
public List<Application> getApplications(String apiKey) throws IOException {
    List<Application> result = new ArrayList<Application>();
    URI url = null;
    try {
        url = new URI(API_URL + APPLICATIONS_ENDPOINT);
    } catch (URISyntaxException e) {
        // no need to handle this
    }
    HttpGet request = new HttpGet(url);
    setHeaders(request, apiKey);
    CloseableHttpClient client = getHttpClient(url);
    ResponseHandler<ApplicationList> rh = new ResponseHandler<ApplicationList>() {
        @Override
        public ApplicationList handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            Gson gson = new GsonBuilder().create();
            Reader reader = new InputStreamReader(entity.getContent());
            return gson.fromJson(reader, ApplicationList.class);
        }
    };
    try {
        ApplicationList response = client.execute(request, rh);
        result.addAll(response.getApplications());
    } finally {
        client.close();
    }
    return result;
}

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

private <T> T toObj(Request req, final Class<T> clazz, IProgressMonitor monitor) throws IOException {
    T obj = null;/*from   www. j av a2s  .  co m*/
    ConnectionManager.register(monitor, req);
    try {
        obj = exec.execute(req).handleResponse(new ResponseHandler<T>() {

            public T handleResponse(final HttpResponse response) throws IOException {
                HttpEntity entity = response.getEntity();
                InputStream in = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    switch (statusLine.getStatusCode()) {
                    case 200:
                        in = getContent(entity);
                        return mapper.readValue(in, clazz);
                    case 204:
                        return null;
                    case 400:
                    case 404:
                        in = getContent(entity);
                        ErrorDescriptor ed = mapper.readValue(in, ErrorDescriptor.class);
                        if (ed != null)
                            throw new ClientProtocolException(
                                    MessageFormat.format(ed.getMessage(), (Object[]) ed.getParameters()));
                    default:
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
            }

            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.jillesvangurp.httpclientfuture.HttpClientWithFutureTest.java

@BeforeClass
public void beforeClass() {
    webServerExecutor = Executors.newSingleThreadExecutor();
    webServer = new WebServer();
    webServerExecutor.execute(webServer);
    clientThreadPool = Executors.newFixedThreadPool(threads);
    PoolingClientConnectionManager conman = new PoolingClientConnectionManager();
    conman.setDefaultMaxPerRoute(threads);
    conman.setMaxTotal(threads);// w  ww.  j  a v  a  2 s  . com
    DefaultHttpClient httpclient = new DefaultHttpClient(conman);
    client = new HttpClientWithFuture<Boolean>(httpclient, clientThreadPool, new ResponseHandler<Boolean>() {
        @Override
        public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            return response.getStatusLine().getStatusCode() == 200;
        }
    });
}