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:com.google.wireless.speed.speedometer.Checkin.java

private String speedometerServiceRequest(String url, String jsonString) throws IOException {

    synchronized (this) {
        if (authCookie == null) {
            if (!checkGetCookie()) {
                throw new IOException("No authCookie yet");
            }/*from   ww w  .  j a v  a2 s.  c o  m*/
        }
    }

    HttpClient client = getNewHttpClient();
    String fullurl = serverUrl + "/" + url;
    HttpPost postMethod = new HttpPost(fullurl);

    StringEntity se;
    try {
        se = new StringEntity(jsonString);
    } catch (UnsupportedEncodingException e) {
        throw new IOException(e.getMessage());
    }
    postMethod.setEntity(se);
    postMethod.setHeader("Accept", "application/json");
    postMethod.setHeader("Content-type", "application/json");
    // TODO(mdw): This should not be needed
    postMethod.setHeader("Cookie", authCookie.getName() + "=" + authCookie.getValue());

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    Log.i(SpeedometerApp.TAG, "Sending request: " + fullurl);
    String result = client.execute(postMethod, responseHandler);
    return result;
}

From source file:com.gimranov.zandy.app.task.ZoteroAPITask.java

/**
 * Executes the specified APIRequest and handles the response
 * //from   www .java  2s  . com
 * This is done synchronously; use the the AsyncTask interface for calls
 * from the UI thread.
 * 
 * @param req
 * @return
 */
public static String issue(APIRequest req, Database db) {
    // Check that the method makes sense
    String method = req.method.toLowerCase();
    if (!method.equals("get") && !method.equals("post") && !method.equals("delete") && !method.equals("put")) {
        // TODO Throw an exception here.
        Log.e(TAG, "Invalid method: " + method);
        return null;
    }
    String resp = "";
    try {
        // Append content=json everywhere, if we don't have it yet
        if (req.query.indexOf("content=json") == -1) {
            if (req.query.indexOf("?") != -1) {
                req.query += "&content=json";
            } else {
                req.query += "?content=json";
            }
        }

        // Append the key, if defined, to all requests
        if (req.key != null && req.key != "") {
            req.query += "&key=" + req.key;

        }
        if (method.equals("put")) {
            req.query = req.query.replace("content=json&", "");
        }
        Log.i(TAG, "Request " + req.method + ": " + req.query);

        URI uri = new URI(req.query);
        HttpClient client = new DefaultHttpClient();
        // The default implementation includes an Expect: header, which
        // confuses the Zotero servers.
        client.getParams().setParameter("http.protocol.expect-continue", false);
        // We also need to send our data nice and raw.
        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        /* It would be good to rework this mess to be less repetitive */
        if (method.equals("post")) {
            HttpPost request = new HttpPost();
            request.setURI(uri);

            // Set headers if necessary
            if (req.ifMatch != null) {
                request.setHeader("If-Match", req.ifMatch);
            }
            if (req.contentType != null) {
                request.setHeader("Content-Type", req.contentType);
            }
            if (req.body != null) {
                Log.d(TAG, "Post body: " + req.body);
                // Force the encoding here
                StringEntity entity = new StringEntity(req.body, "UTF-8");
                request.setEntity(entity);
            }
            if (req.disposition.equals("xml")) {
                HttpResponse hr = client.execute(request);
                int code = hr.getStatusLine().getStatusCode();
                Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase());
                if (code < 400) {
                    HttpEntity he = hr.getEntity();
                    InputStream in = he.getContent();
                    XMLResponseParser parse = new XMLResponseParser(in);
                    if (req.updateKey != null && req.updateType != null)
                        parse.update(req.updateType, req.updateKey);
                    // The response on POST in XML mode (new item) is a feed
                    parse.parse(XMLResponseParser.MODE_FEED, uri.toString(), db);
                    resp = "XML was parsed.";
                } else {
                    Log.e(TAG, "Not parsing non-XML response, code >= 400");
                    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                    hr.getEntity().writeTo(ostream);
                    Log.e(TAG, "Error Body: " + ostream.toString());
                    Log.e(TAG, "Post Body:" + req.body);
                }
            } else {
                BasicResponseHandler brh = new BasicResponseHandler();
                try {
                    resp = client.execute(request, brh);
                    req.onSuccess(db);
                } catch (ClientProtocolException e) {
                    Log.e(TAG, "Exception thrown issuing POST request: ", e);
                    req.onFailure(db);
                }
            }
        } else if (method.equals("put")) {
            HttpPut request = new HttpPut();
            request.setURI(uri);

            // Set headers if necessary
            if (req.ifMatch != null) {
                request.setHeader("If-Match", req.ifMatch);
            }
            if (req.contentType != null) {
                request.setHeader("Content-Type", req.contentType);
            }
            if (req.body != null) {
                // Force the encoding here
                StringEntity entity = new StringEntity(req.body, "UTF-8");
                request.setEntity(entity);
            }
            if (req.disposition.equals("xml")) {
                HttpResponse hr = client.execute(request);
                int code = hr.getStatusLine().getStatusCode();
                Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase());
                if (code < 400) {
                    HttpEntity he = hr.getEntity();
                    InputStream in = he.getContent();
                    XMLResponseParser parse = new XMLResponseParser(in);
                    parse.parse(XMLResponseParser.MODE_ENTRY, uri.toString(), db);
                    resp = "XML was parsed.";
                    // TODO
                    req.onSuccess(db);
                } else {
                    Log.e(TAG, "Not parsing non-XML response, code >= 400");
                    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                    hr.getEntity().writeTo(ostream);
                    Log.e(TAG, "Error Body: " + ostream.toString());
                    Log.e(TAG, "Put Body:" + req.body);
                    // TODO
                    req.onFailure(db);
                    // "Precondition Failed"
                    // The item changed server-side, so we have a conflict to resolve...
                    // XXX This is a hard problem.
                    if (code == 412) {
                        Log.e(TAG, "Skipping dirtied item with server-side changes as well");
                    }
                }
            } else {
                BasicResponseHandler brh = new BasicResponseHandler();
                try {
                    resp = client.execute(request, brh);
                    req.onSuccess(db);
                } catch (ClientProtocolException e) {
                    Log.e(TAG, "Exception thrown issuing PUT request: ", e);
                    req.onFailure(db);
                }
            }
        } else if (method.equals("delete")) {
            HttpDelete request = new HttpDelete();
            request.setURI(uri);
            if (req.ifMatch != null) {
                request.setHeader("If-Match", req.ifMatch);
            }

            BasicResponseHandler brh = new BasicResponseHandler();
            try {
                resp = client.execute(request, brh);
                req.onSuccess(db);
            } catch (ClientProtocolException e) {
                Log.e(TAG, "Exception thrown issuing DELETE request: ", e);
                req.onFailure(db);
            }
        } else {
            HttpGet request = new HttpGet();
            request.setURI(uri);
            if (req.contentType != null) {
                request.setHeader("Content-Type", req.contentType);
            }
            if (req.disposition.equals("xml")) {
                HttpResponse hr = client.execute(request);
                int code = hr.getStatusLine().getStatusCode();
                Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase());
                if (code < 400) {
                    HttpEntity he = hr.getEntity();
                    InputStream in = he.getContent();
                    XMLResponseParser parse = new XMLResponseParser(in);
                    // We can tell from the URL whether we have a single item or a feed
                    int mode = (uri.toString().indexOf("/items?") == -1 && uri.toString().indexOf("/top?") == -1
                            && uri.toString().indexOf("/collections?") == -1
                            && uri.toString().indexOf("/children?") == -1) ? XMLResponseParser.MODE_ENTRY
                                    : XMLResponseParser.MODE_FEED;
                    parse.parse(mode, uri.toString(), db);
                    resp = "XML was parsed.";
                    // TODO
                    req.onSuccess(db);
                } else {
                    Log.e(TAG, "Not parsing non-XML response, code >= 400");
                    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                    hr.getEntity().writeTo(ostream);
                    Log.e(TAG, "Error Body: " + ostream.toString());
                    Log.e(TAG, "Put Body:" + req.body);
                    // TODO
                    req.onFailure(db);
                    // "Precondition Failed"
                    // The item changed server-side, so we have a conflict to resolve...
                    // XXX This is a hard problem.
                    if (code == 412) {
                        Log.e(TAG, "Skipping dirtied item with server-side changes as well");
                    }
                }
            } else {
                BasicResponseHandler brh = new BasicResponseHandler();
                try {
                    resp = client.execute(request, brh);
                    req.onSuccess(db);
                } catch (ClientProtocolException e) {
                    Log.e(TAG, "Exception thrown issuing GET request: ", e);
                    req.onFailure(db);
                }
            }
        }
        Log.i(TAG, "Response: " + resp);
    } catch (IOException e) {
        Log.e(TAG, "Connection error", e);
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI error", e);
    }
    return resp;
}

From source file:eu.fthevenet.binjr.sources.jrds.adapters.JrdsDataAdapter.java

private String getJsonTree(String tabName, String argName, String argValue)
        throws DataAdapterException, URISyntaxException {
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("tab", tabName));
    if (argName != null && argValue != null && argValue.trim().length() > 0) {
        params.add(new BasicNameValuePair(argName, argValue));
    }/* www. ja  v a  2 s.c om*/
    String entityString = doHttpGet(craftRequestUri("/jsontree", params), new BasicResponseHandler());
    logger.trace(entityString);
    return entityString;
}

From source file:com.mobiperf.speedometer.Checkin.java

private String speedometerServiceRequest(String url, String jsonString) throws IOException {

    synchronized (this) {
        if (authCookie == null) {
            if (!checkGetCookie()) {
                throw new IOException("No authCookie yet");
            }/* ww w. ja v  a 2  s  .  c om*/
        }
    }

    HttpClient client = getNewHttpClient();
    String fullurl = serverUrl + "/" + url;
    HttpPost postMethod = new HttpPost(fullurl);

    StringEntity se;
    try {
        se = new StringEntity(jsonString);
    } catch (UnsupportedEncodingException e) {
        throw new IOException(e.getMessage());
    }
    postMethod.setEntity(se);
    postMethod.setHeader("Accept", "application/json");
    postMethod.setHeader("Content-type", "application/json");
    // TODO(mdw): This should not be needed
    postMethod.setHeader("Cookie", authCookie.getName() + "=" + authCookie.getValue());

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    Logger.i("Sending request: " + fullurl);
    String result = client.execute(postMethod, responseHandler);
    return result;
}

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

/**
 * This method tests the @link{DawgPound#unreserve()} API , and verifies the response.
 *///from   ww w  .j  a  va  2  s .  c  om
@Test(groups = "rest")
public void unreserveTest() throws ClientProtocolException, IOException {
    String deviceId = MetaStbBuilder.getUID(UID_PREF);
    addStb(deviceId, mac);

    String expectedToken = "sathy";
    reserve(expectedToken, deviceId);
    Assert.assertTrue(isReserved(deviceId).contains(expectedToken));

    String url = BASE_URL + "unreserve/" + deviceId;
    logger.info("Unreserve URL : " + url);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

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

    Assert.assertNotNull(responseBody, "While trying to unreserve a device ID, response received is null.");
    Assert.assertTrue(responseBody.contains(expectedToken), String.format(
            "Unreserve response body(%s) does not contains the token(%s).", responseBody, expectedToken));

    responseBody = isReserved(deviceId);
    Assert.assertFalse(responseBody.contains(expectedToken),
            String.format("The device ID does not get unreserved. Response body(%s) returned with token(%s).",
                    responseBody, expectedToken));
}

From source file:com.ywh.train.logic.TrainClient.java

/**
 * ?/*  w  w  w  .j  a  v a  2 s  .c o m*/
 * @param from
 * @param to
 * @param startDate
 * @param rangDate
 * @return
 */
public List<TrainQueryInfo> queryTrain(String from, String to, String startDate, String rangDate) {
    log.debug("-------------------query train start-------------------");
    if (rangDate == null || rangDate.isEmpty()) {
        rangDate = "00:00--24:00";
    }
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("method", "queryLeftTicket"));
    parameters.add(new BasicNameValuePair("includeStudent", "00"));
    parameters.add(new BasicNameValuePair("orderRequest.from_station_telecode", Util.getCityCode(from)));
    parameters.add(new BasicNameValuePair("orderRequest.start_time_str", rangDate));
    parameters.add(new BasicNameValuePair("orderRequest.to_station_telecode", Util.getCityCode(to)));
    parameters.add(new BasicNameValuePair("orderRequest.train_date", startDate));
    parameters.add(new BasicNameValuePair("orderRequest.train_no", ""));
    parameters.add(new BasicNameValuePair("seatTypeAndNum", ""));
    parameters.add(new BasicNameValuePair("trainClass", "QB#D#Z#T#K#QT#"));
    parameters.add(new BasicNameValuePair("trainPassType", "QB"));
    HttpGet get = new HttpGet(Constants.QUERY_TRAIN_URL + URLEncodedUtils.format(parameters, HTTP.UTF_8));
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = null;
    List<TrainQueryInfo> all = new ArrayList<TrainQueryInfo>();
    try {
        responseBody = httpclient.execute(get, responseHandler);
        all = Util.parserQueryInfo(responseBody, startDate);
        //         for(TrainQueryInfo tInfo : all) {
        //            System.out.println(tInfo);
        //         }
    } catch (Exception e) {
        log.error(e);
    }
    log.debug("-------------------query train end-------------------");
    return all;

}

From source file:com.github.thebigs.nzbmatrixapi.NZBMatrixApi.java

/**
 * Does the hevy lifting of making the http GET request to the nzbmatrix api using apache's http client libraries
 *
 * @param uri       web address to access (including params)
 * @param parser    parser to call when a response is received
 *
 * @return  returns a subclass of Response, this should be casted to the type of response returned by the ResponseParser given
 *
 * @throws ClientProtocolException/*  w w  w. j  a  v a 2 s . com*/
 * @throws IOException
 * @throws NZBMatrixApiException
 */
private Response doApiCall(final String uri, final Parser parser)
        throws ClientProtocolException, IOException, NZBMatrixApiException {
    final HttpClient httpclient = new DefaultHttpClient();

    final HttpGet httpget = new HttpGet(uri);

    // uncomment this to see all of the request queries as they are submitted.
    //        System.out.println("executing request " + httpget.getURI());

    // Create a response handler
    final ResponseHandler<String> responseHandler = new BasicResponseHandler();
    final String responseBody = httpclient.execute(httpget, responseHandler);

    httpclient.getConnectionManager().shutdown();
    return parser.parseResponse(responseBody);
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Performs the login using user and password
 * /*from   w w  w . j  av a  2 s.com*/
 * @param user user to authenticate
 * @param password password to authenticate
 * @param url http URL to call
 * @param httpclient hhtp client already created
 * @throws ClientProtocolException if any errors occurs on calling the
 *             servlet
 * @throws IOException if I/O error occurs
 */
private static void login(String user, String password, String url, HttpClient httpclient)
        throws ClientProtocolException, IOException {
    // account info in a properties
    Properties properties = new Properties();
    properties.setProperty(USER_PROPERTY_KEY, user);
    properties.setProperty(PASSWORD_PROPERTY_KEY, password);
    StringWriter writer = new StringWriter();
    properties.store(writer, "Account info");
    // login

    // concats URL with query string
    String completeUrl = url + HttpUtil.LOGIN_QUERY_STRING;
    StringEntity entity = new StringEntity(writer.toString(), ContentType.create("text/plain", "UTF-8"));

    // prepares POST request and basic response handler
    HttpPost httppost = new HttpPost(completeUrl);
    httppost.setEntity(entity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    // executes and no parsing
    // result must be only a string
    httpclient.execute(httppost, responseHandler);
}

From source file:com.android.nobadgift.DashboardActivity.java

public void retrieveProductInfo(String barcode) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(
            "https://www.googleapis.com/shopping/search/v1/public/products?key=AIzaSyAy_I77Os63-PKfuxDc4eY_scgo-aylCq4&country=US&q="
                    + barcode);/*from  ww  w. j a  va2s.  c  o m*/
    ResponseHandler<String> handler = new BasicResponseHandler();
    String result = "";
    try {
        result = httpclient.execute(request, handler);
        Log.d("Result", result);
        JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
        JSONArray items = object.getJSONArray("items");
        JSONObject item = (JSONObject) new JSONTokener(items.getString(0)).nextValue();
        String productInfo = item.getString("product");

        JSONObject product = (JSONObject) new JSONTokener(productInfo).nextValue();
        itemName = product.getString("title");
        itemURL = product.getString("link");

        JSONArray images = product.getJSONArray("images");
        JSONObject image = (JSONObject) new JSONTokener(images.getString(0)).nextValue();
        imageURL = image.getString("link");

        JSONObject vendors = product.getJSONObject("author");
        vendorInfo = vendors.getString("name");

        JSONArray prices = product.getJSONArray("inventories");
        JSONObject price = (JSONObject) new JSONTokener(prices.getString(0)).nextValue();
        priceInfo = price.getString("price");

        Log.d("API - itemName", itemName);
        Log.d("API - itemURL", itemURL);
        Log.d("API - imageURL", imageURL);
        Log.d("API - author", vendorInfo);
        Log.d("API - price", priceInfo);

        urlContent = barcode;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
}