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:org.hobbit.spatiotemporalbenchmark.transformations.value.AddressFromNominatim.java

public static String getAddress(double latitude, double longitude) {
    String strAddress = "";
    String point = latitude + "," + longitude;

    String url = "http://nominatim.openstreetmap.org/reverse?format=json&lat=" + latitude + "&lon=" + longitude
            + "&addressdetails=1&accept-language=en";

    HttpPost httppost = new HttpPost(url);
    HttpClient httpclient = new DefaultHttpClient();
    String result = "";
    try {//from w ww. j  a v  a  2s .c o m
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntityGet = response.getEntity();
        if (resEntityGet != null) {
            result = EntityUtils.toString(resEntityGet);
        }
    } catch (Exception e) {
        System.out.println("Exception:" + e);
    }
    try {
        if (result != null) {
            JSONObject json = new JSONObject(result);
            strAddress = json.get("display_name").toString();
        }
    } catch (Exception e) {
    }
    try {
        if (!strAddress.equals("")) {
            pointAddressMap.put(point, strAddress);
            FileUtils.writeStringToFile(f, point + "=" + strAddress + "\n", true);
        }
    } catch (IOException ex) {
        Logger.getLogger(CoordinatesToAddress.class.getName()).log(Level.SEVERE, null, ex);
    }
    return strAddress;
}

From source file:com.datatorrent.demos.mapreduce.Util.java

public static String getJsonForURL(String url) {
    HttpClient httpclient = new DefaultHttpClient();
    logger.debug(url);/*ww  w  .  j a va  2  s . c o  m*/
    try {

        HttpGet httpget = new HttpGet(url);

        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody;
        try {
            responseBody = httpclient.execute(httpget, responseHandler);

        } catch (ClientProtocolException e) {
            logger.debug(e.getMessage());
            return null;

        } catch (IOException e) {
            logger.debug(e.getMessage());
            return null;
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return null;
        }
        return responseBody.trim();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:Main.java

public static byte[] doPostSubmit(String url, Map<String, Object> params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost();
    try {/*from  w w  w. ja  v  a 2  s  .co m*/

        List<NameValuePair> list = new ArrayList<NameValuePair>();

        for (Entry<String, Object> entry : params.entrySet()) {
            NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
            list.add(nameValuePair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
        HttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toByteArray(entity);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:se.vgregion.pubsub.push.impl.HttpUtil.java

public static DefaultHttpClient getClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    //ConnManagerParams.setMaxTotalConnections(client.getParams(), 100);
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 10000);

    return client;
}

From source file:vodafone.free2txt.HttpClientSingleton.java

public static HttpClient getInstance() {
    if (instance == null) {
        instance = new DefaultHttpClient();
        HttpParams httpParams = instance.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
        HttpConnectionParams.setSoTimeout(httpParams, 10000);
    }//from   w  w w.  j av a 2 s  .  c  o m
    return instance;
}

From source file:com.fpmislata.clientejson.ClienteProductoTest.java

private static List<Producto> getListProducto(String url) throws IOException {
    // Crea el cliente para realizar la conexion
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // Crea el mtodo con el que va a realizar la operacion
    HttpGet httpGet = new HttpGet(url);
    // Aade las cabeceras al metodo
    httpGet.addHeader("accept", "application/json; charset=UTF-8");
    httpGet.addHeader("Content-type", "application/json; charset=UTF-8");
    // Invocamos el servicio rest y obtenemos la respuesta
    HttpResponse response = httpClient.execute(httpGet);
    // Obtenemos un objeto String como respuesta del response
    String lista = readObject(response);
    // Creamos el objeto Gson que parsear los objetos a JSON, excluyendo los que no tienen la anotacion @Expose
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    // Creamos el tipo generico que nos va a permitir devolver la lista a partir del JSON que esta en el String
    Type type = new TypeToken<List<Producto>>() {
    }.getType();//from   ww  w.  j a v  a2  s. co m
    // Parseamos el String lista a un objeto con el gson, devolviendo as un objeto List<Categoria>
    return gson.fromJson(lista, type);
}

From source file:es.deustotech.piramide.utils.net.RestClient.java

public static HttpEntity connect(String url, HttpEntity httpEntity) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.content-charset", "UTF-8");
    httpClient.setParams(params);//w w w.  jav  a2  s  .c o  m
    final HttpGet httpGet = new HttpGet(url); //request object
    HttpResponse response = null;

    try {
        response = httpClient.execute(httpGet);
    } catch (ClientProtocolException cpe) {
        Log.d(Constants.TAG, cpe.getMessage());
    } catch (IOException ioe) {
        Log.d(Constants.TAG, ioe.getMessage());
    }
    return httpEntity = response.getEntity();
}

From source file:com.zhaosen.util.HttpClientUtil.java

License:asdf

@SuppressWarnings({ "rawtypes", "unchecked" })
public static String httpPost(String url, String param) throws ClientProtocolException, IOException {
    new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    ArrayList params = new ArrayList();
    params.add(new BasicNameValuePair("data", param));
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    HttpResponse response = (new DefaultHttpClient()).execute(httpPost);
    if (response.getStatusLine().getStatusCode() == 200) {
        String result = EntityUtils.toString(response.getEntity());
        return result;
    } else {/*  w ww . java  2 s.c o m*/
        return "";
    }
}

From source file:org.guohai.android.cta.utility.HttpRest.java

/**
 * HTTPPost?/*from   w  w w.j av a 2 s .  c  o m*/
 * @param url POST?
 * @param pairs ?
 * @return ?JOSN?null
 */
public static ResultInfo HttpPostClient(String url, List<NameValuePair> pairs) {
    //create http client
    HttpClient client = new DefaultHttpClient();
    //create post request
    HttpPost httpPost = new HttpPost(url);
    //return value
    ResultInfo result = new ResultInfo();
    //init eroor value
    result.State = -1000;
    result.Message = "posterror";

    HttpEntity entity;
    try {
        entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e(TAG, e.getMessage());
        return result;
    }
    httpPost.setEntity(entity);

    //??POST? 
    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entityHtml = response.getEntity();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entityHtml.getContent(), "UTF-8"));
            String line = null;
            String reString = "";
            while ((line = reader.readLine()) != null) {
                reString += line;
            }
            if (entityHtml != null) {
                entityHtml.consumeContent();
            }
            Log.i(TAG, reString);
            JSONObject jsonObj;

            try {
                jsonObj = new JSONObject(reString);
                result.State = jsonObj.getInt("state");
                result.Message = jsonObj.getString("message");
                return result;
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }
            return result;
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e(TAG, e.getMessage());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e(TAG, e.getMessage());
    }
    return result;
}

From source file:org.hobbit.spatiotemporalbenchmark.transformations.value.AddressFromGoogleMapsApi.java

public static String getAddress(double latitude, double longitude) {
    String strAddress = "";
    String point = latitude + "," + longitude;
    String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude
            + "&sensor=true&language=en";

    HttpPost httppost = new HttpPost(url);
    HttpClient httpclient = new DefaultHttpClient();
    String result = "";
    try {/*w  ww  .jav a2s .  c  o m*/
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntityGet = response.getEntity();
        if (resEntityGet != null) {
            result = EntityUtils.toString(resEntityGet);
        }
    } catch (Exception e) {
        System.out.println("Exception:" + e);
    }
    try {
        /*Keeps the first address form the results*/
        if (result != null) {
            JSONObject json = new JSONObject(result);
            JSONArray ja = json.getJSONArray("results");
            //System.out.println(result.toString());
            for (int i = 0; i < 1; i++) {
                strAddress = ja.getJSONObject(i).getString("formatted_address");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!strAddress.equals("")) {
            pointAddressMap.put(point, strAddress);
            FileUtils.writeStringToFile(f, point + "=" + strAddress + "\n", true);
        }
    } catch (IOException ex) {
        Logger.getLogger(CoordinatesToAddress.class.getName()).log(Level.SEVERE, null, ex);
    }
    return strAddress;
}