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.genesys.gms.demo.DemoActivity.java

/**
 * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
 * messages to your app. Not needed for this demo since the device sends upstream messages
 * to a server that echoes back the message using the 'from' address in the message.
 *//*  w  w  w.jav  a  2s .  c o m*/
private void sendRegistrationIdToBackend(String regid) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(
            "http://ec2-54-147-250-15.compute-1.amazonaws.com:8080/genesys/1/notification/subscription");
    String json = "{\"subscriberId\":\"Foobar\",\"notificationDetails\":{\"deviceId\": \"" + regid
            + "\", \"type\":\"gcm\"},\"expire\":180000000, \"filter\":\"test.foo\"}";
    try {
        httpPost.setEntity(new StringEntity(json));
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    ResponseHandler<String> handler = new BasicResponseHandler();
    String result = null;
    try {
        result = httpclient.execute(httpPost, handler);
        Log.i(TAG, "Registration result for " + regid + " is " + result);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    Log.i(TAG, result);
}

From source file:uf.edu.encDetailActivity.java

public String getData(String mac) {
    //Data should be verified before calling this code. no verification done here.
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(getString(R.string.registryURL));
    try {//from   w w  w  .j a va2s .  c o  m
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("mac", mac));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler).replace('\n', ' ').trim();
        //JSONObject response=new JSONObject(responseBody);
        Log.i(TAG, "Registration Response: " + responseBody);
        return responseBody;

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    return null;
}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

public VerifyResult verify(final String number, final String brand, final String from, final int length,
        final Locale locale, final LineType type) throws IOException, SAXException {
    if (number == null || brand == null)
        throw new IllegalArgumentException("number and brand parameters are mandatory.");
    if (length > 0 && length != 4 && length != 6)
        throw new IllegalArgumentException("code length must be 4 or 6.");

    log.debug("HTTP-Number-Verify Client .. to [ " + number + " ] brand [ " + brand + " ] ");

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

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    params.add(new BasicNameValuePair("number", number));
    params.add(new BasicNameValuePair("brand", brand));

    if (from != null)
        params.add(new BasicNameValuePair("sender_id", from));

    if (length > 0)
        params.add(new BasicNameValuePair("code_length", String.valueOf(length)));

    if (locale != null)
        params.add(//from   w  ww  . j  a  v  a 2 s  . c  o  m
                new BasicNameValuePair("lg", (locale.getLanguage() + "-" + locale.getCountry()).toLowerCase()));

    if (type != null)
        params.add(new BasicNameValuePair("require_type", type.toString()));

    String verifyBaseUrl = this.baseUrl + PATH_VERIFY;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST method and execute to submit the request
    String response = null;
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(verifyBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = verifyBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");

        try {
            if (this.httpClient == null)
                this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout)
                        .getNewHttpClient();
            HttpResponse httpResponse = this.httpClient.execute(method);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status != 200)
                throw new Exception(
                        "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception e) {
            method.abort();
            log.info("communication failure: " + e);
            String exceptionMsg = e.getMessage();
            if (exceptionMsg.indexOf("Read timed out") >= 0) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass == 1) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }

            // return a COMMS failure ...
            return new VerifyResult(BaseResult.STATUS_COMMS_FAILURE, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true);
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if (!"verify_response".equals(root.getNodeName()))
        throw new IOException("No valid response found [ " + response + "] ");

    return parseVerifyResult(root);
}

From source file:net.sourceforge.subsonic.service.AudioScrobblerService.java

private String[] executeRequest(HttpUriRequest request) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 15000);

    try {/*from  w ww  .j av  a2 s.  c  om*/
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(request, responseHandler);
        return response.split("\\n");

    } finally {
        client.getConnectionManager().shutdown();
    }
}

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

/**
 * This method tests the @link{DawgPound#reservePolitely()} API with already reserved device ,
 * and verifies the response./*from  w  w  w  .  j  a v a  2  s  .  c o m*/
 */
@Test(groups = "rest")
public void reservePolitelyWithExistingReservationTest() throws ClientProtocolException, IOException {
    String deviceId = MetaStbBuilder.getUID(UID_PREF);
    addStb(deviceId, mac);

    String token = "abcd";
    String expectedToken = "sathy";
    int status = reserve(expectedToken, deviceId);
    Assert.assertEquals(status, 200, "Could not reserve the box.");

    long exp = System.currentTimeMillis() + RESERVE_EXPIRATION_TIME_OFFSET;
    String expiration = String.valueOf(exp);
    String url = BASE_URL + "reserve/" + token + "/" + deviceId + "/" + expiration;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpclient.execute(httppost, responseHandler);
    Assert.assertNotNull(responseBody,
            "Response received is null while trying to reserve an already reserved device id.");
    Assert.assertTrue(responseBody.contains(expectedToken),
            String.format("Failed to find token(%s) presence in the response body(%s) of reserve politely.",
                    expectedToken, responseBody));

    // confirm reserved by the given token
    responseBody = isReserved(deviceId);
    Assert.assertTrue(responseBody.contains(expectedToken),
            String.format("Failed to find the token(%s) in response(%s) of device id reserve details.",
                    expectedToken, responseBody));

}

From source file:dataServer.StorageRESTClientManager.java

public boolean insertKPIStorage(String kpiInfo) {

    // Default HTTP response and common properties for responses
    HttpResponse response = null;//from  w  w w.  ja v a  2  s  .  c  o m
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    try {
        HttpPost query = new HttpPost(StreamPipes);
        query.setHeader("Content-type", "application/json");
        query.setEntity(new StringEntity(kpiInfo));

        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");
        System.out.println(kpiInfo);
        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");
        System.out.println(query.toString());
        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");

        response = client.execute(query);

        System.out.println("\n\n\nResponse:\n" + response.toString());

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {

            //throw new RuntimeException("Failed! HTTP error code: " + status);
            //apagar kpi da BD
            System.out.println("Error accessing storage: " + status);

            return false;
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        //result
        return true;

    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
        return false;
    }
}

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

/**
 * ???//  w  ww .jav a2s .  co m
 * @param randCode
 * @param token
 * @param user
 * @param train
 * @return
 */
public Result submiOrder(String randCode, String token, List<UserInfo> users, TrainQueryInfo train) {
    log.debug("-------------------submit order start-------------------");
    Result rs = new Result();
    HttpPost post = new HttpPost(Constants.SUBMIT_URL);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    for (int i = 0; i < users.size(); i++) {
        formparams.add(new BasicNameValuePair("checkbox" + i, "" + i));
    }
    formparams.add(new BasicNameValuePair("checkbox9", "Y"));
    formparams.add(new BasicNameValuePair("checkbox9", "Y"));
    formparams.add(new BasicNameValuePair("checkbox9", "Y"));
    formparams.add(new BasicNameValuePair("checkbox9", "Y"));
    formparams.add(new BasicNameValuePair("checkbox9", "Y"));
    for (UserInfo user : users) {
        formparams.add(new BasicNameValuePair("oldPassengers", user.getSimpleText())); //
    }
    for (int i = users.size(); i < 5; i++) {
        formparams.add(new BasicNameValuePair("oldPassengers", ""));
    }
    formparams
            .add(new BasicNameValuePair("orderRequest.bed_level_order_num", "000000000000000000000000000000"));
    formparams.add(new BasicNameValuePair("orderRequest.cancel_flag", "1"));
    formparams.add(new BasicNameValuePair("orderRequest.end_time", train.getEndTime())); //"18:21"
    formparams.add(new BasicNameValuePair("orderRequest.from_station_name", train.getFromStation())); //""
    formparams.add(new BasicNameValuePair("orderRequest.from_station_telecode", train.getFromStationCode())); //"AOH"
    formparams.add(new BasicNameValuePair("orderRequest.id_mode", "Y")); //"Y"
    formparams.add(new BasicNameValuePair("orderRequest.reserve_flag", "A"));
    formparams.add(new BasicNameValuePair("orderRequest.seat_type_code", ""));
    formparams.add(new BasicNameValuePair("orderRequest.start_time", train.getStartTime()));//"09:08"
    formparams.add(new BasicNameValuePair("orderRequest.station_train_code", train.getTrainNo())); //"D105"
    formparams.add(new BasicNameValuePair("orderRequest.ticket_type_order_num", ""));
    formparams.add(new BasicNameValuePair("orderRequest.to_station_name", train.getToStation())); //""
    formparams.add(new BasicNameValuePair("orderRequest.to_station_telecode", train.getToStationCode())); //"CSQ"
    formparams.add(new BasicNameValuePair("orderRequest.train_date", train.getTrainDate())); //"2011-11-28"
    formparams.add(new BasicNameValuePair("orderRequest.train_no", train.getTrainCode())); // "5l0000D10502"
    formparams.add(new BasicNameValuePair("org.apache.struts.taglib.html.TOKEN", token));
    for (UserInfo user : users) {
        formparams.add(new BasicNameValuePair("passengerTickets", user.getText())); //
    }
    for (int i = 1; i <= users.size(); i++) {
        UserInfo user = users.get(i - 1);
        formparams.add(new BasicNameValuePair("passenger_" + i + "_cardno", user.getID())); //
        formparams.add(new BasicNameValuePair("passenger_" + i + "_cardtype", user.getCardType())); //"1"
        formparams.add(new BasicNameValuePair("passenger_" + i + "_mobileno", user.getPhone())); //
        formparams.add(new BasicNameValuePair("passenger_" + i + "_name", user.getName())); //
        formparams.add(new BasicNameValuePair("passenger_" + i + "_seat", user.getSeatType())); //"O"
        formparams.add(new BasicNameValuePair("passenger_" + i + "_ticket", user.getTickType())); //"1"
    }
    formparams.add(new BasicNameValuePair("randCode", randCode));
    formparams.add(new BasicNameValuePair("textfield", "?"));
    String responseBody = null;
    try {
        UrlEncodedFormEntity uef = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
        post.setEntity(uef);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = httpclient.execute(post, responseHandler);
        String ans = Util.getMessageFromHtml(responseBody);
        if (ans.isEmpty()) {
            rs.setState(Result.UNCERTAINTY);
            rs.setMsg("??");
        } else {
            if (ans.contains("?")) {
                rs.setState(Result.CANCEL_TIMES_TOO_MUCH);
                rs.setMsg(ans);
            } else if (ans.contains("???")) {
                rs.setState(Result.RAND_CODE_ERROR);
                rs.setMsg(ans);
            } else if (ans.contains("??")) {
                rs.setState(Result.REPEAT_BUY_TICKET);
                rs.setMsg(ans);
            } else if (ans.contains("??")) {
                rs.setState(Result.ERROR_CARD_NUMBER);
                rs.setMsg(ans);
            } else {
                rs.setState(Result.OTHER);
                rs.setMsg(ans);
            }
        }
        log.debug(ans);
    } catch (Exception e) {
        log.error(e);
    }
    log.debug("-------------------submit order end-------------------");
    return rs;
}

From source file:com.jelastic.JelasticService.java

DeployResponse deploy(AuthenticationResponse authentication, UploadResponse upLoader) {
    DeployResponse deployResponse = null;
    try {// w ww  .j  ava 2 s . c  o  m
        DefaultHttpClient httpclient = getHttpClient();
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("charset", "UTF-8"));
        qparams.add(new BasicNameValuePair("session", authentication.getSession()));
        qparams.add(new BasicNameValuePair("archiveUri", upLoader.getFile()));
        qparams.add(new BasicNameValuePair("archiveName", upLoader.getName()));
        qparams.add(new BasicNameValuePair("newContext", getContext()));
        qparams.add(new BasicNameValuePair("domain", getEnvironment()));

        for (NameValuePair nameValuePair : qparams) {
            project.log(nameValuePair.getName() + " : " + nameValuePair.getValue(), Project.MSG_DEBUG);
        }

        URI uri = URIUtils.createURI(getProtocol(), getApiHoster(), getPort(), getUrlDeploy(),
                URLEncodedUtils.format(qparams, "UTF-8"), null);
        project.log("Deploy url : " + uri.toString(), Project.MSG_DEBUG);
        HttpGet httpPost = new HttpGet(uri);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpPost, responseHandler);
        project.log("Deploy response : " + responseBody, Project.MSG_DEBUG);

        deployResponse = deserialize(responseBody, DeployResponse.class);
    } catch (URISyntaxException | IOException e) {
        project.log(e.getMessage(), Project.MSG_ERR);
    }
    return deployResponse;
}

From source file:co.realtime.ortc.OrtcModule.java

private void getPresence(final String channel) {
    Runnable task = new Runnable() {
        private HttpClient hc;

        public void run() {
            if (!client.getIsConnected()) {
                fireException("Not connected");
            } else {
                KrollDict kd = new KrollDict();
                kd.put("channel", channel);
                String result = "";
                String error = "";
                String sUrl = client.getUrl();
                sUrl += "/presence/" + aKey + "/" + aToken + "/" + channel;
                try {
                    hc = new DefaultHttpClient();
                    hc.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
                    HttpGet hg = new HttpGet(sUrl);
                    ResponseHandler<String> rh = new BasicResponseHandler();
                    result = hc.execute(hg, rh);
                } catch (Exception e) {
                    error = e.getMessage();
                }//from  w w w .  ja va  2s  .  co m
                kd.put("result", result);
                kd.put("error", error);
                fireEvent("onPresence", kd);
            }
        }
    };
    new Thread(task).start();
}

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

/**
 * Returns the job by its ID. If is not in output queue, normal <code>Object</code> is returned.
 * @param user user to authenticate//from   w w w  .j  a  va 2 s .c o m
 * @param password password to authenticate
 * @param url http URL to call
 * @param jobId jobId
 * @return Object Job instance of a normal <code>Object</code> is not ended
 * @throws SubmitException if errors occur
 */
public static Object getEndedJobByID(String user, String password, String url, String jobId)
        throws SubmitException {
    // creates a HTTP client
    CloseableHttpClient httpclient = null;
    boolean loggedIn = false;
    try {
        httpclient = createHttpClient(url);
        // prepares the entity to send via HTTP
        XStream streamer = new XStream();

        login(user, password, url, httpclient);
        loggedIn = true;
        // concats URL with query string
        String completeUrl = url + HttpUtil.ENDE_JOBID_QUERY_STRING + "?jobId=" + jobId;
        // prepares POST request and basic response handler
        HttpGet httpget = new HttpGet(completeUrl);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // executes and no parsing
        // result must be only a string
        String responseBody = httpclient.execute(httpget, responseHandler);
        return streamer.fromXML(responseBody.trim());
    } catch (KeyManagementException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (UnrecoverableKeyException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (NoSuchAlgorithmException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (KeyStoreException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (URISyntaxException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (ClientProtocolException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (IOException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } finally {
        if (loggedIn) {
            try {
                logout(url, httpclient);
            } catch (Exception e) {
                // debug
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
        }
        // close http client
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}