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

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

Introduction

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

Prototype

public DefaultHttpClient() 

Source Link

Usage

From source file:com.melchor629.musicote.Utils.java

public static ArrayList getHashMapFromUrl(String url) {
    //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    //StrictMode.setThreadPolicy(policy);
    HashMap map = new HashMap();
    try {//from  ww w  .  j  a v  a2s .  co m
        long time = System.currentTimeMillis();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

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

        //BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF8"), 8192);
        StringBuilder sb = new StringBuilder();
        byte[] buff = new byte[256];
        int length = is.read(buff);
        sb.append(new String(buff, 0, length));
        while ((length = is.read(buff)) != -1) {
            sb.append(new String(buff, 0, length));
        }
        is.close();
        Log.d("MainActivity", String.format("JSON Downloaded in %dms", System.currentTimeMillis() - time));

        time = System.currentTimeMillis();
        Gson gson = new Gson();
        String s = sb.toString();
        map = gson.fromJson(s, map.getClass());
        Log.d("MainActivity", String.format("JSON parsed in %dms", System.currentTimeMillis() - time));
        return (ArrayList) map.get("canciones");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Log.e("Utils", "El archivo recibido no es json");
    }
    return null;
}

From source file:com.qcloud.CloudClient.java

public CloudClient() {
    mClient = new DefaultHttpClient();
    mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5 * 1000);
}

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

@Override
protected HttpClient newHttpClient() {
    return new DefaultHttpClient();
}

From source file:com.tinyhydra.botd.GoogleOperations.java

public static List<JavaShop> GetShops(Handler handler, Location currentLocation, String placesApiKey) {
    // Use google places to get all the shops within '500' (I believe meters is the default measurement they use)
    // make a list of JavaShops and pass it to the ListView adapter
    List<JavaShop> shopList = new ArrayList<JavaShop>();
    try {// ww w.j a va 2 s .  c  o m
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        int accuracy = Math.round(currentLocation.getAccuracy());
        if (accuracy < 500)
            accuracy = 500;
        request.setURI(URI.create("https://maps.googleapis.com/maps/api/place/search/json?location="
                + currentLocation.getLatitude() + "," + currentLocation.getLongitude() + "&radius=" + accuracy
                + "&types=" + URLEncoder.encode("cafe|restaurant|food", "UTF-8")
                + "&keyword=coffee&sensor=true&key=" + placesApiKey));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }

        JSONObject predictions = new JSONObject(sb.toString());
        // Google passes back a status string. if we screw up, it won't say "OK". Alert the user.
        String jstatus = predictions.getString("status");
        if (jstatus.equals("ZERO_RESULTS")) {
            Utils.PostToastMessageToHandler(handler, "No shops found in your area.", Toast.LENGTH_SHORT);
            return shopList;
        } else if (!jstatus.equals("OK")) {
            Utils.PostToastMessageToHandler(handler, "Error retrieving local shops.", Toast.LENGTH_SHORT);
            return shopList;
        }

        // This section may fail if there's no results, but we'll just display an empty list.
        //TODO: alert the user and cancel the dialog if this fails
        JSONArray ja = new JSONArray(predictions.getString("results"));

        for (int i = 0; i < ja.length(); i++) {
            JSONObject jo = (JSONObject) ja.get(i);
            shopList.add(new JavaShop(jo.getString("name"), jo.getString("id"), "", jo.getString("reference"),
                    jo.getString("vicinity")));
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return shopList;
}

From source file:org.aliuge.crawler.bootsStrap.JobManager.java

/**
 * /* w  ww  .  j a  va2s  .com*/
 * 
 * @param jobTag
 */
public static void saveJobStatus(String jobTag) {
    @SuppressWarnings("unused")
    CloseableHttpClient httpClient = new DefaultHttpClient();
    /*HttpGet get = new HttpGet("http://127.0.0.1:" + StartServer.PORT
    + StartServer.CONTEXT + "/stop.do?id=" + getJob(jobTag).getId());*/
    /*try {
       httpClient.execute(get);
    } catch (ClientProtocolException e) {
       e.printStackTrace();
    } catch (IOException e) {
       e.printStackTrace();
    }*/
}

From source file:models.Collection.java

public static RestResponse findByID(Long id, String token) throws IOException {
    RestResponse restResponse = new RestResponse();
    //TODO insecure ssl hack
    HttpClient httpClient = new DefaultHttpClient();
    SSLSocketFactory sf = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
            .getScheme("https").getSocketFactory();
    sf.setHostnameVerifier(new AllowAllHostnameVerifier());

    HttpGet request = new HttpGet(Application.baseRestUrl + "/collections/" + id + "?expand=all");
    request.setHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    request.addHeader("rest-dspace-token", token);
    HttpResponse httpResponse = httpClient.execute(request);

    JsonNode collNode = Json.parse(httpResponse.getEntity().getContent());

    Collection collection = new Collection();

    if (collNode.size() > 0) {
        collection = Collection.parseCollectionFromJSON(collNode);
    }/*from   w ww  .  j  a v a 2  s. c  o m*/

    restResponse.httpResponse = httpResponse;
    restResponse.endpoint = request.getURI().toString();

    ObjectMapper mapper = new ObjectMapper();
    String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(collection);
    restResponse.jsonString = pretty;

    restResponse.modelObject = collection;

    return restResponse;
}

From source file:com.jts.main.helper.Http.java

public static String sendPost(String url, URLParameter param) {
    String retval = "";
    HttpClient httpClient = new DefaultHttpClient();
    try {//from  w  ww  . ja v  a  2  s  .  c  o m
        HttpPost request = new HttpPost(My.base_url + url);
        StringEntity params = new StringEntity(param.get());
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        // handle response here...
        retval = org.apache.http.util.EntityUtils.toString(response.getEntity());
        org.apache.http.util.EntityUtils.consume(response.getEntity());
    } catch (IOException | ParseException ex) {
        errMsg = ex.getMessage();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return retval;
}

From source file:com.skalski.raspberrycontrol.Mjpeg.Mjpeg_InputStream.java

public static Mjpeg_InputStream read(String url) throws IOException {
    HttpResponse res;/*from   w ww .j a v  a 2  s .  com*/
    DefaultHttpClient httpclient = new DefaultHttpClient();

    res = httpclient.execute(new HttpGet(URI.create(url)));
    return new Mjpeg_InputStream(res.getEntity().getContent());
}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * Used to insert an element//from w w w. j  av a2 s.c  o m
 * 
 * @param url
 *       Element URI
 * @param c
 *       The element represented with a JSON
 * @return
 *       The response
 */
public static HttpResponse doPost(String url, JSONObject c) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);
    StringEntity s = null;
    try {
        s = new StringEntity(c.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    try {
        return httpclient.execute(request);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:com.abombrecords.amt_unlocker.AMT_Unlocker.java

public static boolean UnlockDoor(String Username, String Password, String DoorPIN) throws Exception {
    boolean bSuccess = false;

    //Log.d(LogTag, "Login");   
    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpPost httpost = new HttpPost("http://acemonstertoys.org/node?destination=node");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("op", "Log in"));
    nvps.add(new BasicNameValuePair("name", Username));
    nvps.add(new BasicNameValuePair("pass", Password));
    nvps.add(new BasicNameValuePair("openid.return_to",
            "http://acemonstertoys.org/openid/authenticate?destination=node"));
    nvps.add(new BasicNameValuePair("form_id", "user_login_block"));
    nvps.add(new BasicNameValuePair("form_build_id", "form-4d6478bc67a79eda5e36c01499ba4c88"));

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

    HttpResponse response = httpclient.execute(httpost);
    HttpEntity entity = response.getEntity();

    //Log.d(LogTag, "Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();/*from   w w w .  jav  a 2 s .c  om*/
    }

    //Log.d(LogTag, "Post Login cookies:");
    // look for drupal_uid and fail out if it isn't there
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        //Log.d(LogTag, "None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            //Log.d(LogTag, "- " + cookies.get(i).toString());

            if (cookies.get(i).getName().equals("drupal_uid")) {
                bSuccess = true;
            }
        }
    }

    if (bSuccess) {
        HttpPost httpost2 = new HttpPost("http://acemonstertoys.org/membership");

        List<NameValuePair> nvps2 = new ArrayList<NameValuePair>();
        nvps2.add(new BasicNameValuePair("doorcode", DoorPIN));
        nvps2.add(new BasicNameValuePair("forceit", "Open Door"));

        httpost2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8));

        response = httpclient.execute(httpost2);
        entity = response.getEntity();

        //Log.d(LogTag, "Unlock form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
    }

    httpclient.getConnectionManager().shutdown();

    return bSuccess;
}