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.strato.hidrive.api.bll.file.GetThumbnailGateway.java

@Override
protected ResponseHandler<String> createResponseHandler() {
    super.createResponseHandler();
    return new ResponseHandler<String>() {
        @Override/*from   w w w  . j  a v  a  2  s  .  co  m*/
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                byte[] bytes = EntityUtils.toByteArray(entity);
                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            }
            return DONE_JSON_RESULT;
        }
    };
}

From source file:es.uned.dia.jcsombria.model_elements.softwarelinks.nodejs.HttpTransport.java

public Object send(String request) throws Exception {
    Object response = null;// w w w .j ava 2s .  c  o  m
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverURL.toString());
        System.out.println("Executing request " + httppost.getRequestLine());
        System.out.println(request);
        httppost.setEntity(new StringEntity(request));
        // 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 < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        response = responseBody;
    } finally {
        httpclient.close();
    }
    return response;
}

From source file:org.cleverbus.core.common.directcall.DirectCallHttpImpl.java

@Override
public String makeCall(String callId) throws IOException {
    Assert.hasText(callId, "callId must not be empty");

    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {//from w  w  w . j a  v a2  s. c o  m
        HttpGet httpGet = new HttpGet(localhostUri + RouteConstants.HTTP_URI_PREFIX
                + DirectCallWsRoute.SERVLET_URL + "?" + DirectCallWsRoute.CALL_ID_HEADER + "=" + callId);

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

            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    // successful response
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new IOException(EntityUtils.toString(response.getEntity()));
                }
            }
        };

        return httpClient.execute(httpGet, responseHandler);
    } finally {
        httpClient.close();
    }
}

From source file:org.apache.solr.kelvin.URLQueryPerformer.java

@Override
protected Object performTestQueries(ITestCase testCase, Properties queryParams) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(this.baseUrl);
    for (String paramName : queryParams.stringPropertyNames()) {
        uriBuilder.setParameter(paramName, queryParams.getProperty(paramName));
    }//from w  w w. j  a  v  a 2 s.c  o  m
    URI uri = uriBuilder.build();
    HttpGet httpget = new HttpGet(uri);

    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 < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };
    String responseBody = httpclient.execute(httpget, responseHandler);

    return responseBody;
}

From source file:com.sicongtang.http.httpcomponents.httpclient.basic.ClientWithResponseHandler.java

public void execute(int count, String url) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from www.  ja v  a 2 s  .  c  o  m
        HttpGet httpget = new HttpGet(url);

        System.out.println(count + " Executing request " + httpget.getRequestLine());

        // 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 < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.print("----------------------------------------");
        System.out.println(responseBody);
    } finally {
        httpclient.close();
    }
}

From source file:com.dnastack.bob.service.processor.util.HttpUtils.java

/**
 * Executes GET/POST and obtain the response.
 *
 * @param request request//from   w ww.  j a  v  a2 s .c  o m
 *
 * @return response
 */
public static String executeRequest(HttpRequestBase request) {
    String response = null;

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };

        response = httpclient.execute(request, responseHandler);
    } catch (IOException ex) {
        // ignore, response already set to null
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            // ignore
        }
    }

    return response;
}

From source file:com.controlj.addon.weather.util.HTTPHelper.java

public Document readDocument(String scheme, String host, int port, String path, Map<String, Object> params)
        throws IOException, URISyntaxException {
    URI uri = URIUtils.createURI(scheme, host, port, path, encodeParams(params), null);
    return httpclient.execute(new HttpGet(uri), new ResponseHandler<Document>() {
        //@Override
        public Document handleResponse(HttpResponse response) throws IOException {
            if (response.getStatusLine().getStatusCode() != 200)
                throw new IOException(response.getStatusLine().getReasonPhrase());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String responseString = EntityUtils.toString(entity);
                try {
                    SAXReader reader = new SAXReader();
                    return reader.read(new StringReader(responseString));
                } catch (DocumentException e) {
                    throw (IOException) new IOException("Service returned \"" + responseString + '"')
                            .initCause(e);
                }//from  w ww .j a va2 s. c o m
            }

            throw new IOException("No response");
        }
    });
}

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

@Override
public UserInfo authentic(OAuth2 oauth) {
    CloseableHttpClient hc = HC_BUILDER.build();
    HttpPost httpPost = new HttpPost("http://dev.sj.4399api.net/Rest?ac=checkToken");

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("uid", oauth.getUid()));
    nvps.add(new BasicNameValuePair("access_token", oauth.getCode()));
    nvps.add(new BasicNameValuePair("app_key", "100979"));
    nvps.add(new BasicNameValuePair("app_secret", "da7be84d18a8aec8a5a45bbc6e5889e9"));

    try {/*ww w . j  a  v  a  2  s.  c om*/

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        JSONObject json = 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);
                return JSON.parseObject(str);
            }
        });

        if (json.getIntValue("code") != 10000) {
            throw new OAuth2Exception(json.getString("message"));
        }

        UserInfo info = new UserInfo();
        info.setUsername(getPlatform().getLabel() + "-" + json.getJSONObject("data").getString("username"));
        info.setPlatform(getPlatform());
        return info;
    } catch (IOException ex) {
        throw new OAuth2Exception("4399?", ex);
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }
}

From source file:ca.sqlpower.dao.json.JSONHttpMessageSender.java

public void flush() throws SPPersistenceException {
    try {/*w ww .  j  a va  2 s. com*/
        URI serverURI = getServerURI();
        HttpPost postRequest = new HttpPost(serverURI);
        postRequest.setEntity(new StringEntity(messageArray.toString()));
        postRequest.setHeader("Content-Type", "application/json");
        HttpUriRequest request = postRequest;
        getHttpClient().execute(request, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() >= 400) {
                    throw new ClientProtocolException("HTTP Post request returned an error: " + "Code = "
                            + statusLine.getStatusCode() + ", " + "Reason = " + statusLine.getReasonPhrase());
                }
                return null;
            }
        });
    } catch (URISyntaxException e) {
        throw new SPPersistenceException(null, e);
    } catch (ClientProtocolException e) {
        throw new SPPersistenceException(null, e);
    } catch (IOException e) {
        throw new SPPersistenceException(null, e);
    } finally {
        clearMessageArray();
    }
}

From source file:org.eclipse.vorto.repository.RestClient.java

@SuppressWarnings("restriction")
public <Result> Result executeGet(String query, final Function<String, Result> responseConverter)
        throws ClientProtocolException, IOException {

    CloseableHttpClient client = HttpClients.custom().build();

    HttpUriRequest request = RequestBuilder.get().setConfig(createProxyConfiguration())
            .setUri(createQuery(query)).build();
    return client.execute(request, new ResponseHandler<Result>() {

        @Override//  w ww .ja  v a 2s .c  o  m
        public Result handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            return responseConverter.apply(IOUtils.toString(response.getEntity().getContent()));
        }
    });
}