Example usage for org.apache.http.impl.client DefaultHttpClient execute

List of usage examples for org.apache.http.impl.client DefaultHttpClient execute

Introduction

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

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:com.lambdasoup.panda.PandaHttp.java

static String post(String url, Map<String, String> params, Properties properties) {
    Map<String, String> sParams = signedParams("POST", url, params, properties);
    String flattenParams = canonicalQueryString(sParams);
    String requestUrl = "http://" + properties.getProperty("api-host") + ":80/v2" + url + "?" + flattenParams;

    HttpPost httpPost = new HttpPost(requestUrl);
    DefaultHttpClient httpclient = new DefaultHttpClient();

    String stringResponse = null;

    try {//  ww  w  . j a  va2 s  . c om
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

        httpPost.setEntity(new StringEntity(canonicalQueryString(sParams), "UTF-8"));
        HttpResponse response = httpclient.execute(httpPost);

        stringResponse = EntityUtils.toString(response.getEntity());

    } catch (IOException e) {
        e.printStackTrace();
    }

    return stringResponse;
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

private static int loadCookie() throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet("http://m.surbus.com/tiempo-espera");
    HttpResponse response = httpClient.execute(get);
    HttpEntity entity = response.getEntity();

    if (entity == null) {
        return ERROR_IO;
    }// w ww  .j ava  2s.  co  m

    Scanner scan = new Scanner(entity.getContent());
    StringBuilder strBuilder = new StringBuilder();
    while (scan.hasNextLine()) {
        strBuilder.append(scan.nextLine());
    }
    scan.close();
    if (!strBuilder.toString().contains("id=\"blockResult\" class=\"messageResult\"")) {
        return MANTENIMIENTO;
    }

    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    for (Cookie c : cookies) {
        if (c.getName().contains("ASP.NET_SessionId")) {
            cookie = c.getValue();
        }
    }
    return TODO_OK;
}

From source file:com.pindroid.client.NetworkUtilities.java

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * //from w w  w  . j a  v a2  s  .c  o m
 * @param username The user's username.
 * @param password The user's password.
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return The boolean result indicating whether the user was
 *         successfully authenticated.
 */
public static boolean pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath("v1/posts/update");
    Uri uri = builder.build();

    HttpGet request = new HttpGet(String.valueOf(uri));

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(SCOPE, credentials);

    try {
        resp = client.execute(request);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
            }
            return true;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return false;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return false;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:com.niceapps.app.HttpClient.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {// ww w. j av  a  2 s . c  om
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-Type", "application/json");

        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            JSONObject jsonObjRecv = new JSONObject(EntityUtils.toString(entity));

            return jsonObjRecv;
        } else {
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.fb.fbdemo.LoginUsingActivityActivity.java

public static String parseJSON(String p_url) {
    JSONObject jsonObject = null;/*from w  w w.  java  2s.  co  m*/
    String json = null;
    try {
        // Create a new HTTP Client
        DefaultHttpClient defaultClient = new DefaultHttpClient();
        // Setup the get request
        HttpGet httpGetRequest = new HttpGet(p_url);
        System.out.println("Request URL--->" + p_url);
        // Execute the request in the client
        HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
        // Grab the response
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        json = reader.readLine();
        System.err.println("JSON Response--->" + json);
        // Instantiate a JSON object from the request response
        /*
         * jsonObject = new JSONObject(json); System.out.println("ID=" +
         * jsonObject.getString("id") + "NAME==>" +
         * jsonObject.getString("name") + "Pic==" +
         * jsonObject.getString("picture"));
         * 
         * JSONObject jobj = new
         * JSONObject(jsonObject.getString("picture")); JSONObject m_dataobj
         * = new JSONObject(jobj.getString("data"));
         * System.out.println("^&&&&&&&&&&&&&&&&&&  " +
         * m_dataobj.getString("url"));
         */

    } catch (Exception e) {
        // In your production code handle any errors and catch the
        // individual exceptions
        e.printStackTrace();
    }
    return json;
}

From source file:org.jboss.as.test.integration.security.loginmodules.common.Utils.java

public static HttpResponse authAndGetResponse(String URL, String user, String pass) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;//from   w  w w.ja v  a2  s.c  o  m
    HttpGet httpget = new HttpGet(URL);

    response = httpclient.execute(httpget);

    HttpEntity entity = response.getEntity();
    if (entity != null)
        EntityUtils.consume(entity);

    // We should get the Login Page
    StatusLine statusLine = response.getStatusLine();
    System.out.println("Login form get: " + statusLine);
    assertEquals(200, statusLine.getStatusCode());

    System.out.println("Initial set of cookies:");
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }

    // We should now login with the user name and password
    HttpPost httpost = new HttpPost(URL + "/j_security_check");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("j_username", user));
    nvps.add(new BasicNameValuePair("j_password", pass));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    response = httpclient.execute(httpost);

    int statusCode = response.getStatusLine().getStatusCode();

    assertTrue((302 == statusCode) || (200 == statusCode));
    // Post authentication - if succesfull, we have a 302 and have to redirect
    if (302 == statusCode) {
        entity = response.getEntity();
        if (entity != null) {
            EntityUtils.consume(entity);
        }
        Header locationHeader = response.getFirstHeader("Location");
        String location = locationHeader.getValue();
        HttpGet httpGet = new HttpGet(location);
        response = httpclient.execute(httpGet);
    }

    return response;
}

From source file:core.HttpClient.java

/**
 * downloads the latest file//from  w ww  .j av a  2 s .co  m
 */
public static String downloadUpdatedFile() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpResponse response;
        HttpEntity entity;

        HttpPost httpost = new HttpPost(QUICKTODO_DOWNLOAD_LINK);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("download_update", "true"));

        response = httpclient.execute(httpost);

        entity = response.getEntity();
        if (entity != null) {
            FileOutputStream fos = new FileOutputStream("QuickToDoUpdate.zip");
            entity.writeTo(fos);
            fos.close();
            return "QuickToDoUpdate.zip";
        }
        return null;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.deliciousdroid.client.NetworkUtilities.java

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * /*from w  w w. j a v  a2  s  .co  m*/
 * @param username The user's username.
 * @param password The user's password.
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return The boolean result indicating whether the user was
 *         successfully authenticated.
 */
public static boolean pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(DELICIOUS_AUTHORITY);
    builder.appendEncodedPath("v1/posts/update");
    Uri uri = builder.build();

    HttpGet request = new HttpGet(String.valueOf(uri));

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(SCOPE, credentials);

    try {
        resp = client.execute(request);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
            }
            return true;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return false;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return false;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:pj.rozkladWKD.HttpClient.java

public static JSONObject SendHttpPost(List<NameValuePair> nameValuePairs)
        throws JSONException, ClientProtocolException, IOException {

    // Create a new HttpClient and Post Header  
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.mmaj.nazwa.pl/rozkladwkd/listener2.php");
    nameValuePairs.add(new BasicNameValuePair("app_ver", RozkladWKD.APP_VERSION));

    // Add your data  
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF_8"));

    // Execute HTTP Post Request  
    HttpResponse response = httpclient.execute(httppost);

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        // Read the content stream

        InputStream instream = entity.getContent();
        Header contentEncoding = response.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }//ww  w. j a  v a  2 s. c om

        // convert content stream to a String
        String resultString = convertStreamToString(instream);

        instream.close();
        //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

        // Transform the String into a JSONObject
        if (RozkladWKD.DEBUG_LOG) {
            Log.i(TAG, "result: " + resultString);
        }
        JSONObject jsonObjRecv = new JSONObject(resultString);
        // Raw DEBUG output of our received JSON object:
        if (RozkladWKD.DEBUG_LOG) {
            Log.i(TAG, "<jsonobject>\n" + jsonObjRecv.toString() + "\n</jsonobject>");
        }

        return jsonObjRecv;
    }

    return null;
}

From source file:edu.illinois.whereru.HTTPRequest.java

public static JSONObject makeHttpRequest(String urlString, String method, List<NameValuePair> params) {

    JSONObject jsonObject = null;/*www.ja va2  s .  c  om*/

    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse;

        if (method.equals("POST")) {
            // init post
            HttpPost httpPost = new HttpPost(urlString);
            // set the resource to send
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            // send the request, retrieve response
            httpResponse = httpClient.execute(httpPost);

        } else {
            // GET method
            // formulate url
            String paramString = URLEncodedUtils.format(params, "utf-8");
            urlString += "?" + paramString;
            // init GET
            HttpGet httpGet = new HttpGet(urlString);
            // send the request, retrieve response
            httpResponse = httpClient.execute(httpGet);

        }

        // retrieve content from the response
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream is = httpEntity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        jsonObject = new JSONObject(sb.toString());
    } catch (NullPointerException e) {

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return jsonObject;
}