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

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

Introduction

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

Prototype

T handleResponse(HttpResponse response) throws ClientProtocolException, IOException;

Source Link

Document

Processes an HttpResponse and returns some value corresponding to that response.

Usage

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

/**
 * Login to Bungeni via the OAuth route//from   w  w  w  . j a va 2 s. com
 * @param oauthForwardURL
 * @param oauthCameFromURL
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException 
 */
private String oauthAuthenticate(String oauthForwardURL, String oauthCameFromURL)
        throws UnsupportedEncodingException, IOException {

    final HttpPost post = new HttpPost(oauthForwardURL);
    final HashMap<String, ContentBody> nameValuePairs = new HashMap<String, ContentBody>();
    nameValuePairs.put("login", new StringBody(this.getUser()));
    nameValuePairs.put("password", new StringBody(this.getPassword()));
    nameValuePairs.put("camefrom", new StringBody(oauthCameFromURL));
    nameValuePairs.put("actions.login", new StringBody("login"));
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Set<String> fields = nameValuePairs.keySet();
    for (String fieldName : fields) {
        entity.addPart(fieldName, nameValuePairs.get(fieldName));
    }
    HttpContext context = new BasicHttpContext();
    post.setEntity(entity);
    HttpResponse oauthResponse = client.execute(post, context);
    // if the OAuth page retrieval failed throw an exception
    if (oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException(oauthResponse.getStatusLine().toString());
    }
    String currentUrl = getRequestEndContextURL(context);
    // consume the response
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String sBody = responseHandler.handleResponse(oauthResponse);
    consumeContent(oauthResponse.getEntity());
    return currentUrl;
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public WebResponse getUrl(String sPage, boolean prefix, Map<String, String> reqHeaders) {
    WebResponse wr = null;//from w  w  w  .  j a  v  a2s .c  om

    String pageURL = (prefix ? this.urlBase + sPage : sPage);

    final HttpGet geturl = new HttpGet(pageURL);
    if (null != reqHeaders) {
        Set<String> keys = reqHeaders.keySet();
        for (String key : keys) {
            geturl.setHeader(key, reqHeaders.get(key));
        }
    }
    boolean bState = false;
    try {
        HttpResponse response = client.execute(geturl);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = responseHandler.handleResponse(response);
        int nStatusCode = response.getStatusLine().getStatusCode();
        consumeContent(response.getEntity());
        wr = new WebResponse(responseBody, response);
    } catch (IOException ex) {
        bState = false;
        log.error("Error while accessin url : " + pageURL, ex);
    }
    return wr;

}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

private boolean oauthTokenAccess(OAuthToken token) {
    boolean bstate = false;
    try {//  w  w  w  .j av a  2s. c  o  m
        // /oauth/access-token?client_id={0}&amp;grant_type=authorization_code&amp;code={1}
        Object[] arguments = { this.loginInfo.getCredentials().oauthAppId, token.code, };
        String sAccessTokenUri = MessageFormat.format(this.loginInfo.getCredentials().oauthAccessTokenUri,
                arguments);
        final HttpGet hget = new HttpGet(this.urlBase + sAccessTokenUri);
        HttpContext context = new BasicHttpContext();
        HttpResponse oauthResponse = getClient().execute(hget, context);
        // if the OAuth page retrieval failed throw an exception
        if ((oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                && !("application/json".equals(oauthResponse.getEntity().getContentType().getValue()))) {
            throw new IOException(oauthResponse.getStatusLine().toString());
        }
        // consume the response
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = responseHandler.handleResponse(oauthResponse);
        HashMap<String, String> jsonTokens = parseJSonStream(responseBody);
        jsonTokens.put("authorization_code", token.getCode());
        jsonTokens.put("authorization_state", token.getState());
        this.writeOauthProperties(jsonTokens);
        consumeContent(oauthResponse.getEntity());
        bstate = true;
    } catch (IOException ex) {
        log.error("Error while getting access token", ex);
    }
    return bstate;
}

From source file:org.jenkinsci.plugins.appio.service.AppioService.java

/**
 * @param appName/*w ww . j av  a2s.  c o m*/
 * @return
 * @throws Exception
 */
public AppioAppObject findApp(String appName) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ResponseHandler<String> handler = new BasicResponseHandler();
    AppioAppObject theApp = new AppioAppObject();

    try {
        // App.io Authorization and Content-Type headers
        String appioAuth = "Basic " + apiKey;
        httpGet.addHeader("Authorization", appioAuth);
        httpGet.addHeader("Accept", appio_v1);

        LOGGER.fine("AppioService.findApp() Request");
        HttpResponse response = httpClient.execute(httpHost, httpGet);
        String jsonAppioApps = handler.handleResponse(response);
        LOGGER.fine("AppioService.findApp() Response: " + jsonAppioApps);

        AppioApps appioApps = new Gson().fromJson(jsonAppioApps, AppioApps.class);
        List<AppioAppObject> list = Arrays.asList(appioApps.getApps());
        Iterator<AppioAppObject> iterator = list.iterator();

        boolean foundAppName = false;
        while ((iterator.hasNext()) && (!foundAppName)) {
            AppioAppObject thisApp = iterator.next();

            if (thisApp.getName().equals(appName)) {
                theApp = thisApp;
                foundAppName = true;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            httpClient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
    return theApp;
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public DefaultHttpClient login() throws UnsupportedEncodingException, IOException {
    if (getClient() != null) {
        return getClient();
    }/* w  ww . j  av  a2 s. c  o  m*/
    client = getThreadSafeClient();

    final HttpPost post = new HttpPost(loginUrl);
    final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("login", this.getUser()));
    nameValuePairs.add(new BasicNameValuePair("password", this.getPassword()));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    HttpResponse response = getClient().execute(post);
    String sBody = responseHandler.handleResponse(response);
    System.out.println(sBody);
    consumeContent(response.getEntity());
    return getClient();
}

From source file:com.ridgelineapps.wallpaper.photosite.TumblrUtils.java

private void executeRequest(String url, HttpGet get, ResponseHandler handler) throws IOException {
    HttpEntity entity = null;/*ww  w.  j  a v a 2s  .  c  o  m*/
    HttpHost host = new HttpHost(url, 80, "http");
    try {
        final HttpResponse response = mClient.execute(host, get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entity = response.getEntity();
            final InputStream in = entity.getContent();
            handler.handleResponse(in);
        }
    } finally {
        if (entity != null) {
            entity.consumeContent();
        }
    }
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.CachingHttpClient.java

/**
 * @param request//www . j av a 2 s. co  m
 *            the request to execute
 * @param responseHandler
 *            the response handler
 * @param context
 *            the http context
 * @param <T>
 *            The Return Type Identified by the generic type of the
 *            {@link ResponseHandler}
 * @return T The response type as handled by ResponseHandler
 * @throws IOException
 */
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
        throws IOException {
    HttpResponse resp = execute(request, context);
    return responseHandler.handleResponse(resp);
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.CachingHttpClient.java

/**
 * Execute an {@link HttpRequest} @ a given {@link HttpHost} with a
 * specified {@link ResponseHandler} that will deal with the result of the
 * call using a specific {@link HttpContext}
 * /*from   w  w  w.  j a va  2 s . c  om*/
 * @param target
 *            the target host for the request. Implementations may accept
 *            <code>null</code> if they can still determine a route, for
 *            example to a default target or by inspecting the request.
 * @param request
 *            the request to execute
 * @param responseHandler
 *            the response handler
 * @param context
 *            the context to use for the execution, or <code>null</code> to
 *            use the default context
 * @param <T>
 *            The Return Type Identified by the generic type of the
 *            {@link ResponseHandler}
 * @return T The response type as handled by ResponseHandler
 * @throws IOException
 */
public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler,
        HttpContext context) throws IOException {
    HttpResponse resp = execute(target, request, context);
    return responseHandler.handleResponse(resp);
}

From source file:org.labkey.freezerpro.export.FreezerProExport.java

/**
 * Tests the connection configuration/*from   w ww. j  av  a 2s . c  om*/
 * @return
 * @throws ValidationException
 */
public void testConnection() throws ValidationException {
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(getConfig().getBaseServerUrl());

    try {
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("method", "search_samples"));
        params.add(new BasicNameValuePair("username", getConfig().getUsername()));
        params.add(new BasicNameValuePair("password", getConfig().getPassword()));
        params.add(new BasicNameValuePair("query", ""));
        params.add(new BasicNameValuePair("limit", "1"));

        post.setEntity(new UrlEncodedFormEntity(params));

        ResponseHandler<String> handler = new BasicResponseHandler();
        HttpResponse response = client.execute(post);
        StatusLine status = response.getStatusLine();

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            ExportSamplesResponse samplesResponse = new ExportSamplesResponse(this,
                    handler.handleResponse(response), status.getStatusCode(), null);
            samplesResponse.loadData();
        } else
            throw new ValidationException(
                    "Attempted connection to the FreezerPro server failed with a status code of: "
                            + response.getStatusLine().getStatusCode());
    } catch (Exception e) {
        throw new ValidationException(e.getMessage());
    }
}

From source file:com.marklogic.sesame.functionaltests.util.ConnectedRESTQA.java

public static String[] getHosts() {
    try {/*  www.ja  v  a2s . com*/
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet get = new HttpGet("http://localhost:8002" + "/manage/v2/hosts?format=json");

        HttpResponse response = client.execute(get);
        ResponseHandler<String> handler = new BasicResponseHandler();
        String body = handler.handleResponse(response);
        JsonNode actualObj = new ObjectMapper().readTree(body);
        JsonNode nameNode = actualObj.path("host-default-list").path("list-items");
        //.path("meta").path("list-items").path("list-item");
        List<String> hosts = nameNode.findValuesAsText("nameref");
        String[] s = new String[hosts.size()];
        hosts.toArray(s);
        return s;

    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
    return null;
}