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:net.fluidnexus.FluidNexusAndroid.services.NexusServiceThread.java

/**
 * Check the hash using the API/*from w  w  w . j a  va2  s .  c  o m*/
 */
private boolean checkHash(String message_hash) {
    boolean result = true;

    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(HASH_REQUEST_URL + message_hash + ".json");
        String response = client.execute(request, new BasicResponseHandler());
        JSONObject object = new JSONObject(response);
        result = object.getBoolean("result");
    } catch (JSONException e) {
        log.debug("JSON Error: " + e);
    } catch (IOException e) {
        log.debug("IOException: " + e);
    }
    return result;

}

From source file:fr.natoine.html.HTMLPage.java

@SuppressWarnings("finally")
public String extractFullContentResource(String _url, int _time_to_respond) {
    String response_content = null;
    HttpClient httpclient = new DefaultHttpClient();
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET , "UTF-8");
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-16");
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "ISO-8859-1");
    //US-ASCII//from  w w  w .j  ava2s.com
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "US-ASCII");
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
    //HttpParams params = 
    //HttpClient httpclient = new DefaultHttpClient(params);
    HttpGet httpget = new HttpGet(_url);
    try {
        //Timer pour mettre un dlai sur le temps d'excution de la requte
        //Timer timer = new Timer();
        //timer.schedule(new TimerTaskTooLong(httpget , _url) , _time_to_respond);
        //HttpResponse response = httpclient.execute(httpget);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        if (responseBody != null) {
            response_content = responseBody;
            //      valid = true ;
        }
    } catch (ClientProtocolException e) {
        //   valid = false ;
        System.out.println(
                "[HTMLPage.extractFullContentCssLink] url : " + _url + " doesn't support GET requests !!! ");
        e.printStackTrace();
    } catch (IOException e) {
        //   valid = false ;
        System.out.println(
                "[HTMLPage.extractFullContentCssLink] url : " + _url + " send no data !!! Not responding ... ");
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
        return response_content;
    }
}

From source file:com.ibuildapp.romanblack.TableReservationPlugin.TableReservationEMailSignUpActivity.java

/**
 * Validate input data and signs up new user on iBuildApp.
 *//*from  w ww  .  j a v a 2s  . c  o  m*/
private void registration() {
    if (signUpActive) {
        handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);

        new Thread(new Runnable() {
            public void run() {

                HttpParams params = new BasicHttpParams();
                params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
                HttpClient httpClient = new DefaultHttpClient(params);

                try {
                    HttpPost httpPost = new HttpPost(TableReservationHTTP.SIGNUP_URL);

                    String firstNameString = firstNameEditText.getText().toString();
                    String lastNameString = lastNameEditText.getText().toString();
                    String emailString = emailEditText.getText().toString();
                    String passwordString = passwordEditText.getText().toString();
                    String rePasswordString = rePasswordEditText.getText().toString();

                    MultipartEntity multipartEntity = new MultipartEntity();
                    multipartEntity.addPart("firstname",
                            new StringBody(firstNameString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("lastname",
                            new StringBody(lastNameString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("email", new StringBody(emailString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("password",
                            new StringBody(passwordString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("password_confirm",
                            new StringBody(rePasswordString, Charset.forName("UTF-8")));

                    // add security part
                    multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8")));
                    multipartEntity.addPart("token",
                            new StringBody(Statics.appToken, Charset.forName("UTF-8")));

                    httpPost.setEntity(multipartEntity);

                    String resp = httpClient.execute(httpPost, new BasicResponseHandler());

                    fwUser = JSONParser.parseLoginRequestString(resp);

                    if (fwUser == null) {
                        handler.sendEmptyMessage(EMEIL_IN_USE);
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG);
                        return;
                    }

                    handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG);

                    handler.sendEmptyMessage(CLOSE_ACTIVITY_OK);

                } catch (Exception e) {
                    handler.sendEmptyMessage(CLOSE_ACTIVITY_BAD);
                }

            }
        }).start();
    } else {
        if (firstNameEditText.getText().toString().length() == 0
                || lastNameEditText.getText().toString().length() == 0
                || emailEditText.getText().toString().length() == 0
                || passwordEditText.getText().toString().length() == 0
                || rePasswordEditText.getText().toString().length() == 0) {
            Toast.makeText(this, R.string.alert_registration_fillin_fields, Toast.LENGTH_LONG).show();
            return;
        }

        if (firstNameEditText.getText().toString().equals(lastNameEditText.getText().toString())) {
            Toast.makeText(this, R.string.alert_registration_spam, Toast.LENGTH_LONG).show();
            return;
        }

        if (firstNameEditText.getText().toString().length() <= 2
                || lastNameEditText.getText().toString().length() <= 2) {
            Toast.makeText(this, R.string.alert_registration_two_symbols_name, Toast.LENGTH_LONG).show();
            return;
        }

        String regExpn = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";

        Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(emailEditText.getText().toString());

        if (matcher.matches()) {
        } else {
            Toast.makeText(this, R.string.alert_registration_correct_email, Toast.LENGTH_LONG).show();
            return;
        }

        if (passwordEditText.getText().toString().length() < 4) {
            Toast.makeText(this, R.string.alert_registration_two_symbols_password, Toast.LENGTH_LONG).show();
            return;
        }

        if (!passwordEditText.getText().toString().equals(rePasswordEditText.getText().toString())) {
            Toast.makeText(this, "Passwords don't match.", Toast.LENGTH_LONG).show();
            return;
        }
    }
}

From source file:com.ibuildapp.romanblack.TableReservationPlugin.utils.TableReservationHTTP.java

/**
 * This method sends HTTP request to get list of reservations.
 *
 * @param user      user//from  ww w. j a v a 2  s .  co  m
 * @param orderInfo order info
 * @return result
 */
public static String sendListOrdersRequest(User user, TableReservationInfo orderInfo) {
    HttpParams httpParameters = new BasicHttpParams();
    httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 5000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = null;
    List<NameValuePair> nameValuePairs = null;

    httppost = new HttpPost(LIST_ORDER_URL);
    Log.e(TAG, "LIST_ORDER_URL = " + LIST_ORDER_URL);

    nameValuePairs = new ArrayList<NameValuePair>();

    // user details
    nameValuePairs.add(new BasicNameValuePair("app_id", orderInfo.getAppid()));
    nameValuePairs.add(new BasicNameValuePair("module_id", orderInfo.getModuleid()));
    nameValuePairs.add(new BasicNameValuePair("user_id", user.getAccountId()));

    // add security part
    nameValuePairs.add(new BasicNameValuePair("app_id", Statics.appId));
    nameValuePairs.add(new BasicNameValuePair("token", Statics.appToken));

    // user details
    String userType = null;
    if (user.getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) {
        userType = "facebook";
    } else if (user.getAccountType() == User.ACCOUNT_TYPES.TWITTER) {
        userType = "twitter";
    } else if (user.getAccountType() == User.ACCOUNT_TYPES.IBUILDAPP) {
        userType = "ibuildapp";
    } else if (user.getAccountType() == User.ACCOUNT_TYPES.GUEST) {
        userType = "guest";
    }
    nameValuePairs.add(new BasicNameValuePair("user_type", userType));

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException uEEx) {
        Log.e("", "");
        return "error";
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        String strResponseSaveGoal;
        strResponseSaveGoal = httpclient.execute(httppost, responseHandler);
        String error = JSONParser.parseQueryError(strResponseSaveGoal);

        if (error == null || error.length() == 0) {
            return strResponseSaveGoal;
        } else {
            return "error";
        }

    } catch (ConnectTimeoutException conEx) {
        Log.d("sendListOrdersRequest", "");
        return "error";
    } catch (ClientProtocolException ex) {
        Log.d("sendListOrdersRequest", "");
        return "error";
    } catch (IOException ex) {
        Log.d("sendListOrdersRequest", "");
        return "error";
    }
}

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

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

    if (this.accountSelector == null) {
        accountSelector = new AccountSelector(context);
    }//from  w w  w.j av a2 s. co m
    if (!accountSelector.isAnonymous()) {
        synchronized (this) {
            if (authCookie == null) {
                if (!checkGetCookie()) {
                    throw new IOException("No authCookie yet");
                }
            }
        }
    }

    HttpClient client = getNewHttpClient();
    String fullurl = (accountSelector.isAnonymous() ? "https://openmobiledata.appspot.com/anonymous"
            : "https://openmobiledata.appspot.com") + "/" + url;
    // Logger.i("Checking in to " + fullurl);
    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");
    if (!accountSelector.isAnonymous()) {
        // 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#reservePolitely()} API with non reserved device , and
 * verifies the response.//  w  w  w  .  j  a  v  a 2  s .  c om
 */
@Test(groups = "rest")
public void reservePolitelyTest() throws ClientProtocolException, IOException {
    String deviceId = MetaStbBuilder.getUID(UID_PREF);
    addStb(deviceId, mac);

    int status = unreserve(deviceId);
    Assert.assertTrue(status == 200, "could not unreserve the box");

    String token = "abcd";
    String expectedToken = "abcd";
    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);
    Assert.assertTrue(responseBody.contains(expectedToken));

    // confirm reserved by the given token
    responseBody = isReserved(deviceId);
    Assert.assertTrue(responseBody.contains(expectedToken));
}

From source file:com.thecorpora.qbo.androidapk.RESTClient.java

public int REST_post(String path, String[] data) {
    try {/*w ww.j a v  a 2s  .  co m*/
        if (hasCookie()) {

            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            DefaultHttpClient client = new DefaultHttpClient(httpParams);

            HttpPost post = new HttpPost(path);

            List params = new ArrayList();

            if (data != null) {
                for (int i = 0; i <= data.length / 2; i = i + 2) {
                    params.add(new BasicNameValuePair(data[i], data[i + 1]));
                }
            }

            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);

            post.setEntity(ent);

            //COOKIE
            post.setHeader("Cookie", "session_id=" + cookie.getValue());

            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String responsePOST = client.execute(post, responseHandler);

        } else {
            Log.e(TAG, " You do not have the proper COOKIE therefor this acction can not be made");
            return -1;
        }

    } catch (Exception e) {
        Log.e(TAG, " Error while making a POST petition " + e);
        return -1;
    }

    return 0;

}

From source file:dataServer.StorageRESTClientManager.java

public boolean updateKPIStorage(String kpiInfo) {

    // Default HTTP response and common properties for responses
    HttpResponse response = null;/*  w ww  . j a  v  a2 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);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            //throw new RuntimeException("Failed! HTTP error code: " + status);
            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.lance.commu.fragment.BaseActivity.java

private String sendData1(String requestURL1) throws ClientProtocolException, IOException {

    HttpPost request = makeHttpPost1(requestURL1);
    HttpClient client = new DefaultHttpClient();
    ResponseHandler<String> reshandler = new BasicResponseHandler();
    String result = client.execute(request, reshandler);
    return result;
}

From source file:com.dubsar_dictionary.Dubsar.model.Model.java

/**
 * Retrieve JSON data for this model instance from the server.
 * @return the JSON payload//from w ww . ja v a  2  s .  c  o  m
 * @throws IOException in case of communication error
 */
protected String fetchData() throws IOException {
    ResponseHandler<String> handler = new BasicResponseHandler();

    // DEBT: Take from strings file or constants
    Header header = new BasicHeader("Accept", "application/json");
    HttpGet request = new HttpGet(getUrl());
    request.addHeader(header);

    HttpClient client = getClient();
    String response = null;

    try {
        response = client.execute(request, handler);
    } catch (ConnectionClosedException e) {
        Log.d(TAG, e.getMessage());

        sClient = null;
        client = getClient();
        response = client.execute(request, handler);

        // If it throws again, let it go (consider it a failure)
    }

    return response;
}