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.github.aistomin.jenkins.real.RealJenkins.java

@Override
public String version() throws Exception {
    final Map<String, String> headers = new HashMap<>();
    Executor.newInstance(HttpClientBuilder.create().build()).execute(Request.Post(this.base))
            .handleResponse(new ResponseHandler<Object>() {
                public Object handleResponse(final HttpResponse response)
                        throws ClientProtocolException, IOException {
                    for (final Header header : response.getAllHeaders()) {
                        headers.put(header.getName(), header.getValue());
                    }//from   w  w w .ja  v a  2  s  .  c  om
                    return response;
                }
            });
    return headers.get("X-Jenkins");
}

From source file:br.bireme.scl.CheckUrl.java

public static int check(final String url) {
    if (url == null) {
        throw new NullPointerException();
    }/*w ww.  ja  v a  2s.  c om*/

    final CloseableHttpClient httpclient = HttpClients.createDefault();
    int responseCode = -1;

    try {
        //final HttpHead httpX = new HttpHead(fixUrl(url)); // Some servers return 500
        final HttpGet httpX = new HttpGet(fixUrl(url));
        httpX.setConfig(CONFIG);
        httpX.setHeader(new BasicHeader("User-Agent", "Wget/1.16.1 (linux-gnu)"));
        httpX.setHeader(new BasicHeader("Accept", "*/*"));
        httpX.setHeader(new BasicHeader("Accept-Encoding", "identity"));
        httpX.setHeader(new BasicHeader("Connection", "Keep-Alive"));

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

            @Override
            public Integer handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                return response.getStatusLine().getStatusCode();
            }
        };
        responseCode = httpclient.execute(httpX, responseHandler);
    } catch (Exception ex) {
        responseCode = getExceptionCode(ex);
    } finally {
        try {
            httpclient.close();
        } catch (Exception ioe) {
        }
    }
    return responseCode;
}

From source file:com.kku.apps.pricesearch.util.HttpConnection.java

public static Bitmap getBitmapFromUrl(String url) {

    HttpGet method = new HttpGet(url);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*from   w  w w.j a v a2s .c  o m*/
        BufferedHttpEntity entity = httpClient.execute(method, new ResponseHandler<BufferedHttpEntity>() {

            @Override
            public BufferedHttpEntity handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {

                // Xe?[^XR?[h
                int status = response.getStatusLine().getStatusCode();

                if (HttpStatus.SC_OK != status) {
                    throw new RuntimeException("?MG?[?");
                }
                HttpEntity entity = response.getEntity();
                BufferedHttpEntity bufferEntity = new BufferedHttpEntity(entity);
                return bufferEntity;
            }
        });
        InputStream is = entity.getContent();
        return BitmapFactory.decodeStream(is);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.infinities.keystone4j.PatchClient.java

public JsonNode connect(Object obj) throws ClientProtocolException, IOException {
    String input = JsonUtils.toJsonWithoutPrettyPrint(obj);
    logger.debug("input: {}", input);
    StringEntity requestEntity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w w w  .j av a 2s .  co  m*/
        HttpPatch request = new HttpPatch(url);
        request.addHeader("accept", "application/json");
        request.addHeader("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText());
        request.setEntity(requestEntity);
        ResponseHandler<JsonNode> rh = new ResponseHandler<JsonNode>() {

            @Override
            public JsonNode handleResponse(final HttpResponse response) throws IOException {
                StatusLine statusLine = response.getStatusLine();
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    throw new ClientProtocolException("Response contains no content");
                }
                String output = getStringFromInputStream(entity.getContent());
                logger.debug("output: {}", output);
                assertEquals(200, statusLine.getStatusCode());

                JsonNode node = JsonUtils.convertToJsonNode(output);
                return node;
            }

            private String getStringFromInputStream(InputStream is) {

                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {

                    br = new BufferedReader(new InputStreamReader(is));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return sb.toString();

            }
        };
        JsonNode node = httpclient.execute(request, rh);

        return node;
    } finally {
        httpclient.close();
    }
}

From source file:atc.otn.ckan.client.CKANClient.java

/**
 * //from w  w  w . ja  va 2 s.  co m
 * @return
 */
private ResponseHandler<String> getGenericResponseHandler() {

    // 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();

            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(
                        "Unexpected response status: " + status + EntityUtils.toString(response.getEntity()));
            }
        }
    };

    return responseHandler;

}

From source file:br.edu.ifrn.SuapClient.java

public String getData() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/* w  ww . ja  v  a2  s.com*/
        //Obtem as informaes bsicas do usurio logado no SUAP
        String url = "https://suap.ifrn.edu.br/api/v2/minhas-informacoes/meus-dados/";
        HttpGet httpget = new HttpGet(url);

        httpget.addHeader("Accept", "application/json");
        httpget.addHeader("X-CSRFToken", TOKEN);
        httpget.addHeader("Authorization", AUTH);

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

        // 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();
                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 response = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        return response;
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return "";
}

From source file:com.brett.http.geo.baidu.GeoRequestHttpClient.java

public static JsonNode geoAcquire(String city) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    //    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    try {//from  www .  j a  v  a  2 s.  co  m

        String address = URLEncoder.encode(city, "utf-8");

        String url = "http://api.map.baidu.com/geocoder/v2/?address={address}&output=json&ak=E4805d16520de693a3fe707cdc962045";

        url = url.replaceFirst("\\{address\\}", address);

        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpget.setHeader("Cache-Control", "no-cache");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Referer",
                "http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

        System.out.println("Executing request httpget.getRequestLine() " + 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, "utf-8") : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(HtmlDecoder.decode(responseBody));
        System.out.println(responseBody);

        System.out.println("----------------------------------------");

        ObjectMapper mapper = new ObjectMapper();
        mapper.readValue(responseBody, AddressCoord.class);
        //      JsonNode root = mapper.readTree(responseBody.substring("showLocation&&showLocation(".length(), responseBody.length()-1));

        // {"status":0,"result":{"location":{"lng":116.30783584945,"lat":40.056876296398},"precise":1,"confidence":80,"level":"\u5546\u52a1\u5927\u53a6"}}
        JsonNode root = mapper.readTree(responseBody);

        System.out.println("result : " + city + " = " + root.get("result"));

        return root;

    } finally {
        httpclient.close();
    }
}

From source file:com.netdimensions.client.Client.java

public final <T> T send(final Command<T> command) throws IOException {
    // Authenticate preemptively
    return command.responseParser.value(client.execute(request(command), new ResponseHandler<Element>() {
        @Override/*w w  w. j  a v  a2s.c om*/
        public final Element handleResponse(final HttpResponse response) throws IOException {
            Logger.getLogger("com.netdimensions.client").info(response.getStatusLine().getReasonPhrase());

            switch (response.getStatusLine().getStatusCode()) {
            case HttpStatus.SC_OK:
                return parse(response.getEntity());
            case HttpStatus.SC_UNAUTHORIZED:
                throw new UnauthorizedException(response.getStatusLine().getReasonPhrase());
            default:
                throw new IOException(response.getStatusLine().getReasonPhrase());
            }
        }
    }, context(url)));
}

From source file:project.latex.balloon.writer.HttpDataWriter.java

void sendPostRequest(String rawString) throws IOException {
    String jsonString = getJsonStringFromRawData(rawString);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    StringEntity entity = new StringEntity(jsonString, ContentType.create("plain/text", Consts.UTF_8));
    HttpPost httppost = new HttpPost(receiverUrl);
    httppost.addHeader("content-type", "application/json");
    httppost.setEntity(entity);//from  w  ww  . j a v a2s  . c o m

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

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, 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 contains no content");
            }
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
            StringBuilder stringBuilder = new StringBuilder();
            String line = reader.readLine();
            while (line != null) {
                stringBuilder.append(line);
                line = reader.readLine();
            }
            return stringBuilder.toString();
        }
    };

    String responseString = httpclient.execute(httppost, responseHandler);
    logger.info(responseString);
}

From source file:org.commonjava.couch.test.fixture.RemoteRESTFixture.java

public <T> T get(final String url, final Class<T> type) throws Exception {
    final HttpGet get = new HttpGet(fixup(url));
    try {/*www.  j a v a 2  s .c  om*/
        return http.execute(get, new ResponseHandler<T>() {
            @SuppressWarnings("unchecked")
            @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();
    }
}