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.thoughtmetric.tl.TLLib.java

public static boolean login(String login, String pw, Handler handler, Context context) throws IOException {
    handler.sendEmptyMessage(TLHandler.PROGRESS_LOGIN);

    // Fetch the token
    HtmlCleaner cleaner = TLLib.buildDefaultHtmlCleaner();
    URL url = new URL(LOGIN_URL);
    TagNode node = TLLib.TagNodeFromURLLoginToken(cleaner, url, handler, context);
    String token = null;//from w w  w  .jav a  2 s  .c  o  m
    try {
        TagNode result = (TagNode) node.evaluateXPath("//input")[0];
        token = result.getAttributeByName("value");
    } catch (XPatherException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (token == null) {
        return false;
    }
    // 
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpost = new HttpPost(LOGIN_URL);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair(USER_FIELD, login));
    nvps.add(new BasicNameValuePair(PASS_FIELD, pw));
    nvps.add(new BasicNameValuePair(REMEMBERME, "1"));
    nvps.add(new BasicNameValuePair("stage", "1"));
    nvps.add(new BasicNameValuePair("back_url", ""));
    nvps.add(new BasicNameValuePair("token", token));
    Log.d("token:", token);

    try {
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();

        Header[] headers = response.getHeaders("Set-Cookie");
        if (headers.length > 0) {
            loginName = null;
            loginStatus = false;
        } else {
            loginName = login;
            loginStatus = true;
            cookieStore = httpclient.getCookieStore();
        }

        if (entity != null) {
            entity.consumeContent();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return loginStatus;
}

From source file:me.nytyr.simplebitmapcache.http.HttpBitmapGetter.java

@Override
public Bitmap get(final String URL) {
    // Making HTTP request
    try {/*from w ww .  j  a  v  a  2s  .co  m*/

        final HttpParams httpParams = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParams, httpTimeout);

        HttpConnectionParams.setSoTimeout(httpParams, httpTimeout);
        HttpConnectionParams.setTcpNoDelay(httpParams, true);

        ConnManagerParams.setTimeout(httpParams, httpTimeout);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        HttpGet httpPost = new HttpGet(URL);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        HttpEntity httpEntity = httpResponse.getEntity();
        final FlushedInputStream is = new FlushedInputStream(httpEntity.getContent());

        if (statusCode != 200) {
            Log.e(TAG, "Error downloading image. Status code > " + statusCode);
            return null;
        }
        return BitmapFactory.decodeStream(is);

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

From source file:com.currencyconverter.model.WebService.java

public JSONObject getJson(String url) throws ClientProtocolException, IOException {

    JSONObject jObj = null;//from w ww  . j ava2  s . c o  m
    InputStream is = null;
    String json = "";

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + json + e.toString());
    }

    // return JSON String
    return jObj;
}

From source file:com.qperior.GSAOneBoxProvider.QPOneBoxProviderServletTest.java

private String callHttpGet(String uri) throws Exception {

    HttpGet httpget = new HttpGet(uri);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httpget);

    String actual = "";

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        long len = entity.getContentLength();
        if (len != -1 && len < 2048) {
            actual = EntityUtils.toString(entity);
        } else {/* w  w  w  . ja v  a 2  s.c  o m*/
            // Stream content out
        }
    }

    return actual;
}

From source file:com.qperior.GSAOneBoxProvider.QPOneBoxProviderServletTest.java

private String callHttpPost(String uri) throws Exception {

    HttpPost httppost = new HttpPost(uri);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httppost);

    String actual = "";

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        long len = entity.getContentLength();
        if (len != -1 && len < 2048) {
            actual = EntityUtils.toString(entity);
        } else {//from   w  w  w  . jav  a 2 s  . c  o m
            // Stream content out
        }
    }

    return actual;
}

From source file:WSpatern.ValidTokenWS.java

public void TokenStats(String token) {
    try {//from   w w  w.  j  av  a2  s.co  m
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("http://documenta-dms.com/DMSWS/api/v1/login/" + token);
        HttpResponse response = client.execute(get);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {

            System.out.println(line);
            parseXML(line);

        }
    } catch (IOException ex) {
        Logger.getLogger(ValidTokenWS.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.jboss.as.test.integration.web.cookie.CookieUnitTestCase.java

@Test
public void testCookieRetrievedCorrectly() throws Exception {
    log.info("testCookieRetrievedCorrectly()");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieServlet"));

    // assert that we are able to hit servlet successfully
    int postStatusCode = response.getStatusLine().getStatusCode();
    Header[] postErrorHeaders = response.getHeaders("X-Exception");
    assertTrue("Wrong response code: " + postStatusCode, postStatusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-Exception(" + Arrays.toString(postErrorHeaders) + ") is null", postErrorHeaders.length == 0);

    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    assertTrue("Sever did not set expired cookie on client", checkNoExpiredCookie(cookies));

    for (Cookie cookie : cookies) {
        log.info("Cookie : " + cookie);
        String cookieName = cookie.getName();
        String cookieValue = cookie.getValue();

        if (cookieName.equals("simpleCookie")) {
            assertTrue("cookie value should be jboss", cookieValue.equals("jboss"));
            assertEquals("cookie path", "/jbosstest-cookie", cookie.getPath());
            assertEquals("cookie persistence", false, cookie.isPersistent());
        } else if (cookieName.equals("withSpace")) {
            assertEquals("should be no quote in cookie with space", cookieValue.indexOf("\""), -1);
        } else if (cookieName.equals("comment")) {
            log.info("comment in cookie: " + cookie.getComment());
            // RFC2109:Note that there is no Comment attribute in the Cookie request header
            // corresponding to the one in the Set-Cookie response header. The user
            // agent does not return the comment information to the origin server.

            assertTrue(cookie.getComment() == null);
        } else if (cookieName.equals("withComma")) {
            assertTrue("should contain a comma", cookieValue.indexOf(",") != -1);
        } else if (cookieName.equals("expireIn10Sec")) {
            Date now = new Date();
            log.info("will sleep for 5 seconds to see if cookie expires");
            assertTrue("cookies should not be expired by now",
                    !cookie.isExpired(new Date(now.getTime() + fiveSeconds)));
            log.info("will sleep for 5 more secs and it should expire");
            assertTrue("cookies should be expired by now",
                    cookie.isExpired(new Date(now.getTime() + 2 * fiveSeconds)));
        }/*from  w  ww  .j a va2  s  . co  m*/
    }
}

From source file:WSpatern.FileCategory.java

public void getFile(String token, String id) {
    try {//from ww w  . j  ava  2 s .  c  o  m
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(
                "http://documenta-dms.com/DMSWS/api/v1/file/" + token + "/category_by_id/" + id);
        HttpResponse response = client.execute(get);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {

            System.out.println(line);
            parseXML(line);

        }
    } catch (IOException ex) {
        Logger.getLogger(ValidTokenWS.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.aikidonord.utils.JSONRequest.java

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {/* www  .  j  a v  a 2  s .  c  o m*/
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    //System.out.println("AIKIDONORD : " + json);
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        return null;
    }

    // return JSON String
    return jObj;

}

From source file:edu.isi.karma.webserver.ExtractSpatialInformationFromWikimapiaServiceHandler.java

protected void outputToOSM(String url) throws SQLException, ClientProtocolException, IOException {
    //String url = "http://api.wikimapia.org/?function=box&count=100&lon_min=-118.29244&lat_min=34.01794&lon_max=-118.28&lat_max=34.02587&key=156E90A4-57B03618-05BDBEA0-ED9C6E97-DD2116A6-A5229FEC-091E312A-2856C8BA";      
    this.url = "http://api.wikimapia.org/?function=box&count=100" + url
            + "&key=156E90A4-57B03618-05BDBEA0-ED9C6E97-DD2116A6-A5229FEC-091E312A-2856C8BA";
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(this.url);
    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity);
    FileOutputStream fout = new FileOutputStream(osmFile_path);
    OutputStream bout = new BufferedOutputStream(fout);
    OutputStreamWriter out = new OutputStreamWriter(bout, "UTF8");
    out.write(result);//w  ww  .  j a va  2s. co m
    out.close();
}