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.rubtsov.pageLoader.PageLoader.java

/**
 * function returns string with loaded by url web page
 * @param url url  of page to load//from  ww  w .ja  va 2 s  .  c  o  m
 * @return string with loaded by url web page
 * @throws ClientProtocolException if error on page get occured
 * @throws IOException if error on to string conversion occured
 */
public String getPage(String url) throws ClientProtocolException, IOException, Exception {
    url = url.trim();
    if ((url == null) || (url.isEmpty())) {
        throw new IllegalArgumentException("url parameter is empty");
    }

    if (!url.startsWith("http://")) {
        throw new Exception("url must start with http://");
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpGet);
    try {
        response.getStatusLine();
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);

    } finally {
        httpGet.releaseConnection();
    }
}

From source file:neembuu.vfs.progresscontrol.GeneralThrottleTestMeasurement.java

public GeneralThrottleTestMeasurement() throws Exception {
    controlThrottle = new ControlThrottle(this);
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override/*from   w ww .  j ava 2s  . c o m*/
        public void run() {
            controlThrottle.setVisible(true);
        }
    });

    DefaultHttpClient myClient = new DefaultHttpClient();
    myClient.execute(new HttpGet(
            //"http://neembuu.com/test_videos/test120k.rmvb"

            "http://localhost:8080/LocalFileServer-war/servlet/FileServer?" + "totalFileSpeedLimit=8000&"
            //  + "mode=constantAverageSpeed"
                    + "mode=constantFlow" + "&newConnectionTimemillisec=1&file=wal.avi"

    )).getEntity().writeTo(this);

}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

/**
 * Connects to the SampleSync test server, authenticates the provided
 * username and password.//from www. j  a v a 2  s . c o  m
 *
 * @param username The server account username
 * @param password The server account password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String password, Context context) {
    try {
        final HttpResponse resp;
        final HttpResponse init_resp;
        final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        DefaultHttpClient hClient = getHttpClient(context);
        final HttpPost init_post = new HttpPost(BASE_URL);
        final int first_cookies;
        final ArrayList<SerializableCookie> saveCooks = new ArrayList<SerializableCookie>();
        BasicCookieStore bcs = new BasicCookieStore();

        params.add(new BasicNameValuePair(PARAM_USERNAME, username));
        params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
        params.add(new BasicNameValuePair(PARAM_REMEMBER, "yes"));

        init_resp = hClient.execute(init_post);
        String respString = EntityUtils.toString(init_resp.getEntity());

        List<Cookie> cookies = hClient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            Log.e(TAG, "No cookies gathered first time round");
        }
        first_cookies = cookies.size();
        if (first_cookies != 2) {
            Log.e(TAG, "Should be two cookie to start off with");
        }

        Document doc = Jsoup.parse(respString);
        Elements hiddens = doc.select("div.homepage input[type=hidden]");

        for (Element hidden : hiddens) {
            params.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value")));
        }

        final HttpEntity entity;
        try {
            entity = new UrlEncodedFormEntity(params);
        } catch (final UnsupportedEncodingException e) {
            // this should never happen.
            throw new IllegalStateException(e);
        }
        Log.i(TAG, "Authenticating to: " + AUTH_URI);
        final HttpPost post = new HttpPost(AUTH_URI);
        post.addHeader(entity.getContentType());
        post.setEntity(entity);
        resp = hClient.execute(post);
        String authToken = null;
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //set authtoken here

            cookies = hClient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                Log.e(TAG, "No cookies gathered");
            } else {
                if (cookies.size() == first_cookies + 2) { //we get two new cookies when we log in
                    for (int i = 0; i < cookies.size(); i++) {
                        Cookie cur_cookie = cookies.get(i);
                        if (cur_cookie.isPersistent()) {
                            saveCooks.add(new SerializableCookie(cur_cookie));
                        }
                    }
                    authToken = toString(saveCooks);
                }
            }

        }
        if ((authToken != null) && (authToken.length() > 0)) {
            Log.v(TAG, "Successful authentication");
            return authToken;
        } else {
            Log.e(TAG, "Error authenticating" + resp.getStatusLine());
            return null;
        }
    } catch (final IOException e) {
        Log.e(TAG, "IOException when getting authtoken", e);
        return null;
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }
}

From source file:android.net.http.DefaultHttpClientTest.java

private void testServerClosesOutput(SocketPolicy socketPolicy) throws Exception {
    server.enqueue(/*from  w  w  w.  j  a v a 2  s  .c  o  m*/
            new MockResponse().setBody("This connection won't pool properly").setSocketPolicy(socketPolicy));
    server.enqueue(new MockResponse().setBody("This comes after a busted connection"));
    server.play();

    DefaultHttpClient client = new DefaultHttpClient();

    HttpResponse a = client.execute(new HttpGet(server.getUrl("/a").toURI()));
    assertEquals("This connection won't pool properly", contentToString(a));
    assertEquals(0, server.takeRequest().getSequenceNumber());

    HttpResponse b = client.execute(new HttpGet(server.getUrl("/b").toURI()));
    assertEquals("This comes after a busted connection", contentToString(b));
    // sequence number 0 means the HTTP socket connection was not reused
    assertEquals(0, server.takeRequest().getSequenceNumber());
}

From source file:uk.codingbadgers.SurvivalPlus.error.ReportExceptionRunnable.java

public boolean run() {
    try {//w ww  .j a va 2s . co  m
        List<NameValuePair> data = new ArrayList<NameValuePair>();
        data.add(new BasicNameValuePair("password",
                DigestUtils.md5Hex(SurvivalPlus.getConfigurationManager().getCrashPassword())));
        data.add(new BasicNameValuePair("project", "bFundamentals"));
        data.add(new BasicNameValuePair("cause", getException(throwable)));
        data.add(new BasicNameValuePair("message", getMessage(throwable)));
        data.add(new BasicNameValuePair("st", buildStackTrace(throwable)));
        HttpPost post = new HttpPost("http://server.mcbadgercraft.com/crash/report.php");
        post.setEntity(new UrlEncodedFormEntity(data));

        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse responce = client.execute(post);
        String result = EntityUtils.toString(responce.getEntity());

        if (SurvivalPlus.getConfigurationManager().isDebugEnabled())
            System.out.println(result);

        JSONObject object = (JSONObject) new JSONParser().parse(result);
        boolean success = (Boolean) object.get("success");
        if (!success)
            System.err.println(object.get("error"));
        return success;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:uk.submergedcode.SubmergedCore.error.ReportExceptionRunnable.java

public boolean run() {
    try {/* ww w.  j  a  v a  2 s .co  m*/
        List<NameValuePair> data = new ArrayList<NameValuePair>();
        data.add(new BasicNameValuePair("password",
                DigestUtils.md5Hex(SubmergedCore.getConfigurationManager().getCrashPassword())));
        data.add(new BasicNameValuePair("project", "SubmergedCore"));
        data.add(new BasicNameValuePair("cause", getException(throwable)));
        data.add(new BasicNameValuePair("message", getMessage(throwable)));
        data.add(new BasicNameValuePair("st", buildStackTrace(throwable)));
        HttpPost post = new HttpPost("http://server.mcbadgercraft.com/crash/report.php");
        post.setEntity(new UrlEncodedFormEntity(data));

        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse responce = client.execute(post);
        String result = EntityUtils.toString(responce.getEntity());

        if (SubmergedCore.getConfigurationManager().isDebugEnabled())
            System.out.println(result);

        JSONObject object = (JSONObject) new JSONParser().parse(result);
        boolean success = (Boolean) object.get("success");
        if (!success)
            System.err.println(object.get("error"));
        return success;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:com.droidworks.asynctask.AbsTinyUrlAsyncTask.java

@Override
protected String doInBackground(String... url) {
    String result = null;//from   w  w w  .  j a  v  a2  s. c o m

    try {
        HttpGet getMethod = new HttpGet(TINY_URL_API + url[0]);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpUtils.setConnectionTimeout(httpClient, 10);
        HttpResponse response = httpClient.execute(getMethod);
        result = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        Log.e(getClass().getName(), "Error transforming url", e);
    }

    return result;
}

From source file:edu.stanford.mobisocial.dungbeetle.util.HTTPDownloadTextFileTask.java

@Override
public String doInBackground(String... urls) {
    String response = "";
    for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {/*w  w w.ja  v  a2s .c  o  m*/
            HttpResponse execute = client.execute(httpGet);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                response += s;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return response;
}

From source file:com.fatminds.cmis.AlfrescoCmisHelper.java

/**
 * This is here and needed because Alfresco CMIS and Chemistry don't play nice together for relationship deletes
 * as of Alfresco 3.4.2-5 & Chemistry 0.3.0. The problem is that for whatever reason Chemistry strips the "assoc:" prefix
 * off of the relationship ID that ends up on the end of the Delete URL, like this - /alfresco/service/cmis/rel/assoc:363.
 * Left to its own devices, Relationship.delete() will end up issuing a URL like /alfresco/service/cmis/rel/363, and Alfresco
 * will barf. This will hopefully be fixed in Alfesco 4.x.
 * @param proto//from w  w w .j a v a 2  s .  c  o m
 * @param host
 * @param port
 * @param user
 * @param pass
 * @param assocId
 * @return
 */
public static boolean deleteRelationship(String proto, String host, int port, String user, String pass,
        String assocId) {
    DefaultHttpClient client = new DefaultHttpClient();
    try {
        client.getCredentialsProvider().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, pass));
        HttpDelete delete = new HttpDelete(
                proto + "://" + host + ":" + port + "/alfresco/service/cmis/rel/" + assocId);
        log.info("Sending " + delete.toString());
        HttpResponse resp = client.execute(delete);
        if (resp.getStatusLine().getStatusCode() > 299) { // Alf returns "204 No Content" for success... :-(
            throw new RuntimeException("Get failed (" + resp.getStatusLine().getStatusCode() + ") because "
                    + resp.getStatusLine().getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return true;
}

From source file:piuk.MyRemoteWallet.java

private static String postURL(String request, String urlParameters) throws Exception {
    if (urlParameters.length() > 0) {
        urlParameters += "&";
    }/*from w  w w.  j  a  va  2 s. c  o m*/

    urlParameters += "api_code=" + getApiCode();

    DefaultHttpClient client = new DefaultHttpClient();

    HttpConnectionParams.setConnectionTimeout(client.getParams(), 180000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 180000);

    final HttpPost httpPost = new HttpPost(request);

    httpPost.setEntity(new StringEntity(urlParameters, "application/x-www-form-urlencoded", "UTF-8"));

    final HttpResponse response = client.execute(httpPost);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new Exception("Invalid HTTP Response code " + response.getStatusLine().getStatusCode() + " "
                + IOUtils.toString(response.getEntity().getContent()));
    }

    String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

    return responseString;
}