Example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler.

Prototype

BasicResponseHandler

Source Link

Usage

From source file:tud.time4maps.request.CapabilitiesRequest.java

/**
 * This method handles http get request and returns response string.
 * /*from   ww  w  .j  a  v  a  2s .  c  om*/
 * @param wmsUrl - the wms request url
 * @return response document 
 */
public static String getResponseString(String wmsUrl) {
    HttpClient httpclient = new DefaultHttpClient();

    try {
        String responseBody = "";
        HttpGet httpget = new HttpGet(wmsUrl);

        // Create a response handler
        BasicResponseHandler responseHandler = new BasicResponseHandler();
        try {
            responseBody = httpclient.execute(httpget, responseHandler);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        responseBody = responseBody.replaceAll("\\(", "");
        responseBody = responseBody.replaceAll("\\)", "");

        responseBody = responseBody.replaceAll("\\<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?\\>", "");
        responseBody = responseBody.replaceAll("\\<!\\[CDATA\\[", "");
        responseBody = responseBody.replaceAll("\\]\\]\\>", "");
        responseBody = responseBody.replaceAll("\\", "");

        return responseBody;
    } finally {

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.xx_dev.apn.proxy.test.TestProxyWithHttpClient.java

private void test(String uri, int exceptCode, String exceptHeaderName, String exceptHeaderValue) {
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(2000);/*  w  ww.  j  a v  a 2  s .  c  om*/
    cm.setDefaultMaxPerRoute(40);
    cm.setDefaultConnectionConfig(connectionConfig);

    CloseableHttpClient httpClient = HttpClients.custom()
            .setUserAgent("Mozilla/5.0 xx-dev-web-common httpclient/4.x").setConnectionManager(cm)
            .disableContentCompression().disableCookieManagement().build();

    HttpHost proxy = new HttpHost("127.0.0.1", ApnProxyConfig.getConfig().getPort());

    RequestConfig config = RequestConfig.custom().setProxy(proxy).setExpectContinueEnabled(true)
            .setConnectionRequestTimeout(5000).setConnectTimeout(10000).setSocketTimeout(10000)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    HttpGet request = new HttpGet(uri);
    request.setConfig(config);

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(request);

        Assert.assertEquals(exceptCode, httpResponse.getStatusLine().getStatusCode());
        if (StringUtils.isNotBlank(exceptHeaderName) && StringUtils.isNotBlank(exceptHeaderValue)) {
            Assert.assertEquals(exceptHeaderValue, httpResponse.getFirstHeader(exceptHeaderName).getValue());
        }

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseHandler.handleResponse(httpResponse);

        httpResponse.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:com.primitive.applicationmanager.BaseApplicationManager.java

/**
 * ??????/*  w ww .  jav a  2 s  . c  o m*/
 * @param argUrl
 * @param argParams
 * @return JSONObject
 * @throws ApplicationManagerException
 */
protected JSONObject requestToResponse(final String argUrl, Map<String, String> argParams)
        throws ApplicationManagerException {
    Logger.start();
    Logger.debug("argUrl:" + argUrl);
    if (argParams == null) {
        argParams = new HashMap<String, String>();
    }
    Logger.debug("argParams:" + argParams.toString());
    argParams.put("device", "android");
    if (BuildConfig.DEBUG) {
        argParams.put("mode", "debug");
    }
    argParams.put("protocolVersion", config.protocolVersion.version);

    final HttpClient httpClient = this.createHttpClient();
    String res = null;
    try {
        final HttpPost httpost = new HttpPost(argUrl);
        final JSONObject holder = BaseApplicationManager.getJsonObjectFromMap(argParams);
        final StringEntity se = new StringEntity(holder.toString());

        httpost.setEntity(se);
        httpost.setHeader("Accept", "application/json");
        httpost.setHeader("Content-type", "application/json");
        final BasicResponseHandler responseHandler = new BasicResponseHandler();
        res = httpClient.execute(httpost, responseHandler);
        Logger.debug(res);

        final JSONObject json = new JSONObject(res);
        return json;
    } catch (final Throwable ex) {
        Logger.err(ex);
        throw new ApplicationManagerException(ex);
    }

}

From source file:ClientWithResponseHandler.java

public void sub() throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    try {//from   w ww  .jav a2s .co m
        HttpGet httpget = new HttpGet("https://www.google.com/m8/feeds/contacts/default/full/");

        httpget.addHeader("Authorization",
                "OAuth ya29.AHES6ZRPmOdPH5NegD3vQByXUe_1L2ikXZEbECGPEkwXiDxzPLg9oi8");
        httpget.addHeader("Gdata-version", "3.0");

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

        Header[] headers = httpget.getAllHeaders();
        for (Header temp : headers) {
            System.out.println(temp.getName());
        }
        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.HttpHelper.java

public static void post(PlatformID platformID, String path, String paramName, InputStream data)
        throws CiliaException {

    String url = getURL(platformID, path);

    HttpPost httppost = new HttpPost(url);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    InputStreamBody bin = new InputStreamBody(data, paramName);
    reqEntity.addPart(paramName, bin);/*  www  . ja va  2 s.  c  o m*/

    httppost.setEntity(reqEntity);

    // HTTP request
    HttpClient httpClient = getClient();
    try {
        httpClient.execute(httppost, new BasicResponseHandler());
        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        httpClient.getConnectionManager().shutdown();
        throw new CiliaException("can't perform HTTP PUT request", e);
    }
}

From source file:com.aokp.romcontrol.github.tasks.GetJSONChangelogTask.java

protected Void doInBackground(Void... unused) {
    HttpClient httpClient = null;/*ww w.  j  a  v a  2s .c  o  m*/
    try {
        httpClient = new DefaultHttpClient();
        String url = String.valueOf(STATIC_DEBUG ? "https://raw.github.com/JBirdVegas/tests/master/example.json"
                : mConfig.CHANGELOG_JSON);
        HttpGet requestWebsite = new HttpGet(url);
        Log.d(TAG, "attempting to connect to: " + url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        JSONArray projectCommitsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler));

        // debugging
        if (DEBUG)
            Log.d(TAG, "projectCommitsArray.length() is: " + projectCommitsArray.length());
        if (Config.StaticVars.JSON_SPEW)
            Log.d(TAG, "projectCommitsArray.toString() is: " + projectCommitsArray.toString());

        final ChangelogObject commitObject = new ChangelogObject(new JSONObject());
        for (int i = 0; i < projectCommitsArray.length(); i++) {
            JSONObject projectsObject = (JSONObject) projectCommitsArray.get(i);
            PreferenceScreen newCommitPreference = mCategory.getPreferenceManager()
                    .createPreferenceScreen(mContext);
            commitObject.reParse(projectsObject);
            newCommitPreference.setTitle(commitObject.getSubject());
            newCommitPreference.setSummary(commitObject.getBody());
            newCommitPreference.setKey(commitObject.getCommitHash());
            newCommitPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    mAlertDialog.setCommitAndShow(commitObject);
                    return false;
                }
            });
            mCategory.addPreference(newCommitPreference);
        }
    } catch (HttpResponseException httpError) {
        Log.e(TAG, "bad HTTP response:", httpError);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "client protocal exception:", e);
    } catch (JSONException e) {
        Log.d(TAG, "bad json interaction:", e);
    } catch (IOException e) {
        Log.d(TAG, "io exception:", e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return null;
}

From source file:dk.i2m.drupal.resource.FileResource.java

public boolean delete(Long id) throws HttpResponseException, IOException {
    URLBuilder builder = new URLBuilder(getDc().getHostname());
    builder.add(getDc().getEndpoint());//from   www  . j  av  a2s.  c o m
    builder.add(getAlias());
    builder.add(id);

    HttpDelete method = new HttpDelete(builder.toURI());

    ResponseHandler<String> handler = new BasicResponseHandler();
    String response = getDc().getHttpClient().execute(method, handler);

    return Boolean.valueOf(response);
}

From source file:com.nagazuka.mobile.android.goedkooptanken.service.impl.ZukaService.java

public String download(PlacesParams params) throws NetworkException {
    String response = "";
    try {/*from  w  w w  .j a va 2  s . c om*/
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(constructURL(params));
        //Log.d(TAG, "<< HTTP Request: " + request.toString());

        ResponseHandler<String> handler = new BasicResponseHandler();
        response = httpClient.execute(request, handler);
        //Log.d(TAG, "<< HTTP Response: " + response);

        httpClient.getConnectionManager().shutdown();
    } catch (ClientProtocolException c) {
        c.printStackTrace();
        throw new NetworkException("Er zijn netwerkproblemen opgetreden bij het downloaden van de tankstations",
                c);
    } catch (IOException e) {
        e.printStackTrace();
        throw new NetworkException("Er zijn netwerkproblemen opgetreden bij het downloaden van de tankstations",
                e);

    }

    return response;
}

From source file:com.github.kristofa.test.http.MockHttpServerTest.java

@Test
public void testShouldHandlePostRequests() throws ClientProtocolException, IOException {
    // Given a mock server configured to respond to a POST / with data
    // "Hello World" with an ID
    responseProvider.expect(Method.POST, "/", "text/plain; charset=UTF-8", "Hello World").respondWith(200,
            "text/plain", "ABCD1234");

    // When a request for POST / arrives
    final HttpPost req = new HttpPost(baseUrl + "/");
    req.setEntity(new StringEntity("Hello World", UTF_8));
    final ResponseHandler<String> handler = new BasicResponseHandler();
    final String responseBody = client.execute(req, handler);

    // Then the response is "ABCD1234"
    assertEquals("ABCD1234", responseBody);
}