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:smarthome.FXMLDocumentController.java

public void httpPost(String url) {
    try {/*from   w w  w.  j  a v a2s  .  c  o m*/
        HttpClient Client = new DefaultHttpClient();
        try {
            String SetServerString = "";
            // Create Request to server and get response
            HttpGet httpget = new HttpGet(url);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            SetServerString = Client.execute(httpget, responseHandler);

        } catch (Exception ex) {

        }
    } catch (Exception e) {

    }

}

From source file:com.comcast.dawg.pound.DawgPoundIT.java

/**
 * This method tests the @link{DawgPound#getReservered()} API with valid token, and verifies the
 * response body./*from w w w  . ja v  a  2s.  com*/
 *
 * @throws  IOException
 * @throws  ClientProtocolException
 */
@Test(groups = "rest")
public void getReserveredTest() throws ClientProtocolException, IOException {
    String deviceId = MetaStbBuilder.getUID(UID_PREF);
    addStb(deviceId, mac);

    String token = "sathyv";
    String expectedStr = "\"reserver_key\":\"" + token + "\"";

    int status = reserveTheBox(token, deviceId);
    Assert.assertEquals(status, 200, "Could not reserve the box.");

    String url = BASE_URL + "reserved/token/" + token;
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpclient.execute(httpget, responseHandler);
    Assert.assertNotNull(responseBody, "While trying to get reserved status, response received is null.");
    Assert.assertTrue(responseBody.contains(expectedStr),
            String.format("Failed to find the reserver key(%s) in response(%s).", expectedStr, responseBody));
    Assert.assertTrue(responseBody.contains(deviceId),
            String.format("Failed to find the device ID(%s) in response(%s).", deviceId, responseBody));
}

From source file:com.genericconf.bbbgateway.services.ApiCallExecution.java

final CharSequence makeHttpRequest(HttpClient httpClient, String url) throws Exception {
    HttpGet httpget = new HttpGet(url);
    logger.info("executing request " + httpget.getURI());
    // Create a response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpClient.execute(httpget, responseHandler);
    logger.debug("Response: " + responseBody);
    return responseBody;
}

From source file:edu.vt.vbi.patric.common.DataApiHandler.java

public String solrQuery(SolrCore core, SolrQuery query) {

    String responseBody = null;/*from   w w  w .j ava2  s  . c  om*/
    RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).build();
    try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {

        HttpPost request = new HttpPost(baseUrl + core.getSolrCoreName());

        request.setHeader("Accept", "application/solr+json");
        request.setHeader("Content-Type", "application/solrquery+x-www-form-urlencoded");

        if (token != null) {
            request.setHeader("Authorization", token);
        }

        request.setEntity(new StringEntity(query.toString()));

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = client.execute(request, responseHandler);

    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return responseBody;
}

From source file:org.opendaylight.fpc.notification.HTTPNotifier.java

/**
 * Primary Constructor.// w w  w.  ja va2 s. com
 *
 * @param startSignal - Latch start signal
 * @param blockingNotificationQueue - Blocking Queue assigned to the worker
 */
public HTTPNotifier(CountDownLatch startSignal,
        BlockingQueue<AbstractMap.SimpleEntry<Uri, Notification>> blockingNotificationQueue) {
    this.run = false;
    this.startSignal = startSignal;
    this.blockingNotificationQueue = blockingNotificationQueue;
    handler = new BasicResponseHandler();
    this.api = new DpnAPI2(ZMQClientPool.getInstance().getWorker());
}

From source file:at.alladin.rmbt.client.helper.JSONParser.java

public JSONObject sendJSONToUrl(final URI uri, final JSONObject data) {
    JSONObject jObj = null;//from   w  w w . jav  a 2s. co  m
    String responseBody;

    try {
        final HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 20000);
        HttpConnectionParams.setSoTimeout(params, 20000);
        final HttpClient client = new DefaultHttpClient(params);

        final HttpPost httppost = new HttpPost(uri);

        final StringEntity se = new StringEntity(data.toString(), "UTF-8");

        httppost.setEntity(se);
        httppost.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

        final ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = client.execute(httppost, responseHandler);

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(responseBody);
        } catch (final JSONException e) {
            writeErrorList("Error parsing JSON " + e.toString());
        }

    } catch (final UnsupportedEncodingException e) {
        writeErrorList("Wrong encoding");
        // e.printStackTrace();
    } catch (final HttpResponseException e) {
        writeErrorList(
                "Server responded with Code " + e.getStatusCode() + " and message '" + e.getMessage() + "'");
    } catch (final ClientProtocolException e) {
        writeErrorList("Wrong Protocol");
        // e.printStackTrace();
    } catch (final ConnectTimeoutException e) {
        writeErrorList("ConnectionTimeoutException");
        e.printStackTrace();
    } catch (final IOException e) {
        writeErrorList("IO Exception");
        e.printStackTrace();
    }

    if (jObj == null)
        jObj = createErrorJSON();

    // return JSONObject
    return jObj;
}

From source file:com.travelguide.GuideActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    final String TAG = "Activity2";

    String ln = getIntent().getExtras().getString("tag");
    if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) {
        TextView t1 = (TextView) findViewById(R.id.thanks);
        t1.setText("Gracias por usar mi aplicacin.");

        TextView t2 = (TextView) findViewById(R.id.link);
        t2.setText("Las ubicaciones de visitantes en el interior "
                + getIntent().getExtras().getString("com.travelguide.radius") + " millas para "
                + getIntent().getExtras().getString("com.travelguide.location"));

    } else {/*from  ww w .  jav  a 2s.  com*/
        TextView t1 = (TextView) findViewById(R.id.thanks);
        t1.setText("Thanks for using my App.");

        TextView t2 = (TextView) findViewById(R.id.link);
        t2.setText(
                "Visitor locations found within " + getIntent().getExtras().getString("com.travelguide.radius")
                        + " miles for " + getIntent().getExtras().getString("com.travelguide.location"));

    }

    String url = getIntent().getExtras().getString("com.travelguide.link");
    Log.i(TAG, url);

    try {
        //***** Parsing the xml file*****
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        tgparse myXML_parser = new tgparse();
        xr.setContentHandler(myXML_parser);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url.replace(" ", "%20"));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        Log.i(TAG, "responseBody: " + responseBody);
        ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());
        xr.parse(new InputSource(is));

        Log.i(TAG, "parse complete");

        TextView placename[];
        TextView placeaddress[];
        TextView placerating[];

        tgxml data;
        data = tgparse.getXMLData();
        placename = new TextView[data.getName().size()];
        placeaddress = new TextView[data.getName().size()];
        placerating = new TextView[data.getName().size()];

        webview = (WebView) findViewById(R.id.myWebView);

        //    webview.setBackgroundColor(0);
        //    webview.setBackgroundResource(R.drawable.openbook);

        String stg1 = new String();
        stg1 = "<html>";
        for (int i = 1; i < (data.getName().size()); i++) {
            Log.i(TAG, " " + i);
            Log.i(TAG, "Name= " + data.getName().get(i));
            Log.i(TAG, "Address= " + data.getAddress().get(i));
            Log.i(TAG, "Rating= " + data.getRating().get(i));

            placename[i] = new TextView(this);
            placename[i].setText("Name= " + data.getName().get(i));

            placeaddress[i] = new TextView(this);
            placeaddress[i].setText("Address= " + data.getAddress().get(i));

            placerating[i] = new TextView(this);
            placerating[i].setText("Rating= " + data.getRating().get(i));

            if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) {
                stg1 = stg1 + "Nombre: " + data.getName().get(i) + "<br>" + " Direccin: "
                        + data.getAddress().get(i) + "<br>" + " clasificacin= " + data.getRating().get(i)
                        + "<br>" + "<br>";
            } else {
                stg1 = stg1 + "Name: " + data.getName().get(i) + "<br>" + " Address: "
                        + data.getAddress().get(i) + "<br>" + " Rating= " + data.getRating().get(i) + "<br>"
                        + "<br>";
            }

        }
        stg1 = stg1 + "</html>";
        webview.loadDataWithBaseURL(null, stg1, "text/html", "utf-8", "about:blank");

    } catch (Exception e) {
        Log.i(TAG, "Exception caught", e);

    }

}

From source file:com.pg.newsapp.http.NewsHttpClient.java

/**
 * TODO : ReCheck ...// www  . j  a v a 2 s.c o  m
 * @return
 */
private String executeGet() {
    String result = null;

    try {
        HttpClient httpclient = new DefaultHttpClient();

        if (mValues != null && mValues.size() > 0) {
            StringBuilder sb = new StringBuilder();

            for (String key : mValues.keySet()) {
                String value = mValues.get(key);
                if (sb.toString().length() > 0) {
                    sb.append("&");
                }
                sb.append(key);
                sb.append("=");
                sb.append(value);
            }

            mUrl += "?" + sb.toString();
        }
        HttpGet httpget = new HttpGet(mUrl);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        result = httpclient.execute(httpget, responseHandler);
    } catch (Exception e) {
        Log.w(TAG, "-- executeGet" + e.getMessage());
    }

    return result;
}

From source file:servlet.SecurityServlet.java

private String getUserMailAddressFromJsonResponse(String accessToken, HttpSession httpSession) {
    String email = null;//from www .  j av  a2 s .c  o m
    HttpClient httpclient = new DefaultHttpClient();
    try {
        //         if (accessToken != null && ! "".equals(accessToken)) {
        if (accessToken != null) {
            String newUrl = "https://graph.facebook.com/me/friends?access_token=" + accessToken;
            httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(newUrl);
            System.out.println("Get info from face --> executing request: " + httpget.getURI());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String responseBody = httpclient.execute(httpget, responseHandler);
            JSONObject json = (JSONObject) JSONSerializer.toJSON(responseBody);

            System.out.println("from json " + json.toString());

            String facebookId = json.getString("id");
            String firstName = json.getString("first_name");
            String lastName = json.getString("last_name");
            email = json.getString("email");

            //put user data in session
            httpSession.setAttribute("FACEBOOK_USER",
                    firstName + " " + lastName + ", facebookId:" + facebookId);

        } else {
            System.err.println("Token za facebook je null");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return email;
}

From source file:org.andstatus.app.net.HttpConnectionOAuthApache.java

@Override
public JSONObject postRequest(HttpPost post) throws ConnectionException {
    JSONObject jso = null;/*from  w w w. java 2 s  .  c  o m*/
    String response = null;
    boolean ok = false;
    try {
        if (data.oauthClientKeys.areKeysPresent()) {
            // sign the request to authenticate
            getConsumer().sign(post);
        }
        response = mClient.execute(post, new BasicResponseHandler());
        jso = new JSONObject(response);
        ok = true;
    } catch (HttpResponseException e) {
        ConnectionException e2 = ConnectionException.fromStatusCodeHttp(e.getStatusCode(), "postRequest", e);
        MyLog.i(TAG, e2);
        throw e2;
    } catch (JSONException e) {
        MyLog.i(TAG, "postRequest, response=" + (response == null ? NULL_JSON : response), e);
        throw new ConnectionException(e);
    } catch (Exception e) {
        // We don't catch other exceptions because in fact it's vary difficult to tell
        // what was a real cause of it. So let's make code clearer.
        throw new ConnectionException(e);
    }
    if (!ok) {
        jso = null;
    }
    return jso;
}