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.jesjimher.bicipalma.BicipalmaJsonClient.java

public static JSONArray connect(String url) {

    JSONArray json = new JSONArray();

    try {/*from  w ww  . ja v a 2 s  .c o  m*/
        // Primero conectar a la URL base para capturar el id de sesin
        HttpGet hg = new HttpGet("http://83.36.51.60:8080/eTraffic3/Control?act=mp");
        HttpParams httpParameters = new BasicHttpParams();
        // Poner los timeouts apropiadamente
        int timeoutConnection = 5000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 7000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        DefaultHttpClient hcli = new DefaultHttpClient(httpParameters);
        HttpResponse resp = hcli.execute(hg);
        if (resp.getStatusLine().getStatusCode() == 200) {
            // Con el JSESSIONID, conectar a la URL que recupera el JSON
            String cookie = resp.getFirstHeader("Set-Cookie").getValue().split(";")[0];
            resp.getEntity().consumeContent();
            hg = new HttpGet(
                    "http://83.36.51.60:8080/eTraffic3/DataServer?ele=equ&type=401&li=2.6226425170898&ld=2.6837539672852&ln=39.588022779794&ls=39.555621694894&zoom=15&adm=N&mapId=1&lang=es");
            hg.setHeader("Referer", "http://83.36.51.60:8080/eTraffic3/Control?act=mp");
            hg.addHeader("Cookie", cookie);
            resp = hcli.execute(hg);
            if (resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = resp.getEntity();
                if (he != null) {
                    // A Simple JSON Response Read
                    InputStream instream = he.getContent();
                    // Averiguar el encoding
                    String enc = he.getContentType().getValue();
                    enc = enc.substring(enc.indexOf("charset=") + 8);
                    if (enc.length() <= 0)
                        enc = "ISO-8859-1";
                    String result = convertStreamToString(instream, enc);

                    json = new JSONArray(result);
                    instream.close();
                }
                resp.getEntity().consumeContent();
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return json;
}

From source file:Main.java

/**
 * @author Cheb//w ww  .  jav  a2 s . c o m
 * @param URL - URL to server
 * @param context - context
 * @param mPreferences SharedPreferences
 * downloading JSON from URL
 */
public static String downloadJSON(String URL, Context context, SharedPreferences mPreferences) {
    StringBuilder sb = new StringBuilder();
    DefaultHttpClient mHttpClient = new DefaultHttpClient();
    HttpGet dhttpget = new HttpGet(URL);
    HttpResponse dresponse = null;
    try {
        dresponse = mHttpClient.execute(dhttpget);
    } catch (IOException e) {
        e.printStackTrace();
    }
    int status = dresponse.getStatusLine().getStatusCode();
    if (status == 200) {
        char[] buffer = new char[1];
        try {
            InputStream content = dresponse.getEntity().getContent();
            InputStreamReader isr = new InputStreamReader(content);
            while (isr.read(buffer) != -1) {
                sb.append(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //saving JSON 
        mPreferences = context.getSharedPreferences(TAG_FEED, 0);
        mPreferences.edit().putString(TAG_FEED, sb.toString()).commit();
    } else {
        Log.i("Error", "Connection error : " + Integer.toString(status));
    }
    return sb.toString();
}

From source file:com.unitedcoders.android.gpodroid.services.RSSService.java

private static String getImageUrlFromFeed(Context context, String url) {

    try {/*from   w  w  w. ja  va  2  s. co  m*/
        Document doc;
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        doc = builder.parse(response.getEntity().getContent());
        //            return doc;

        // get Image
        NodeList item = doc.getElementsByTagName("channel");
        Element el = (Element) item.item(0);

        String imageUrl;
        NodeList imagNode = el.getElementsByTagName("image");
        if (imagNode != null) {
            Element ima = (Element) imagNode.item(0);
            if (ima != null) {
                NodeList urlNode = ima.getElementsByTagName("url");
                if (urlNode == null || urlNode.getLength() < 1)
                    imageUrl = null;
                else
                    imageUrl = urlNode.item(0).getFirstChild().getNodeValue();
            } else
                imageUrl = null;
        } else
            imageUrl = null;

        return imageUrl;

    } catch (IOException e) {
        return null; // The network probably died, just return null
    } catch (SAXException e) {
        // Problem parsing the XML, log and return nothing
        Log.e("NCRSS", "Error parsing XML", e);
        return null;
    } catch (Exception e) {
        // Anything else was probably another network problem, fail silently
        return null;
    }
}

From source file:com.yojiokisoft.globish1500.exception.MyUncaughtExceptionHandler.java

/**
 * ?????./* ww  w . j ava 2 s . com*/
 */
private static void postBugReport() {
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    String bug = getFileBody(sBugReportFile);
    nvps.add(new BasicNameValuePair("dev", Build.DEVICE));
    nvps.add(new BasicNameValuePair("mod", Build.MODEL));
    nvps.add(new BasicNameValuePair("sdk", Build.VERSION.SDK));
    nvps.add(new BasicNameValuePair("ver", sVersionName));
    nvps.add(new BasicNameValuePair("bug", bug));
    try {
        HttpPost httpPost = new HttpPost("http://mrp-bug-report.appspot.com/bug");
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.execute(httpPost);
    } catch (IOException e) {
        e.printStackTrace();
    }
    sBugReportFile.delete();
}

From source file:de.nico.asura.tools.JSONParser.java

public static JSONObject getJSONFromUrl(String url) {

    // Make HTTP request
    try {//w  w w  . jav a  2s. com
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    }

    catch (UnsupportedEncodingException e) {
        Log.e("UnsupportedEncodingException", e.toString());
    }

    catch (ClientProtocolException e) {
        Log.e("ClientProtocolException", e.toString());
    }

    catch (IOException e) {
        Log.e("IOException", e.toString());
    }

    try {
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader reader = new BufferedReader(isr, 8);
        StringBuilder sb = new StringBuilder();
        String line;

        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 " + e.toString());
    }

    // return JSON String
    return jObj;

}

From source file:com.mockey.runner.JettyRunner.java

private static void initializeMockey(URL initUrl) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(initUrl.toString());
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    System.out.println("Initialized mockey with request: " + initUrl.toString());
    System.out.println("Response: " + entity.getContent());
}

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

private static Cliente getCliente(String url) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    httpGet.addHeader("accept", "application/json; charset=UTF-8");
    HttpResponse response = httpClient.execute(httpGet);
    String cliente = readObject(response);
    Gson gson = new Gson();
    return gson.fromJson(cliente, Cliente.class);
}

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

private static List<Cliente> getListCliente(String url) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    httpGet.addHeader("accept", "application/json; charset=UTF-8");
    HttpResponse response = httpClient.execute(httpGet);
    String lista = readObject(response);
    Gson gson = new Gson();
    Type type = new TypeToken<List<Cliente>>() {
    }.getType();//from  ww  w.  j a  v  a2 s .c  om
    return gson.fromJson(lista, type);
}

From source file:com.AA.Other.RSSParse.java

/**
 * Get the XML document for the RSS feed
 * @return the XML Document for the feed on success, on error returns null
 *//*from   w  w w.ja  va 2 s . com*/
private static Document getDocument() {
    Document doc = null;
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        //I'm not sure how this handles network timeouts... Needs testing
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(URI);
        HttpResponse response = client.execute(request);
        doc = builder.parse(response.getEntity().getContent());

    } catch (java.io.IOException e) {
        //IO Exception generally implies network error, so just fail silently
        return null;
    } catch (SAXException e) {
        //SAXException means the xml isn't valid. fail and log an error
        Log.e("AARSS", "Parse Exception in RSS feed", e);
        return null;
    } catch (Exception e) {
        //this means either a builder exception or a timeout
        return null;
    }
    return doc;
}

From source file:com.jeffreyawest.http.HTTPAdapterImpl.java

private static String doHTTPMethod(HttpRequestBase pRequest) throws Exception {

    InputStream is = null;//  w w w.  j a  v a 2  s  .  c o m
    StringBuilder sb = new StringBuilder();
    DefaultHttpClient httpClient = new DefaultHttpClient();

    Log.v(LOG_TAG, "doHTTPMethod()");

    try {
        HttpResponse httpResponse = httpClient.execute(pRequest);
        Log.v("HTTPAdapter.doHTTPMethod", "HTTP Status:" + httpResponse.getStatusLine());
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            throw new Exception("HTTP Error: " + httpResponse.getStatusLine());
        }
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (Exception e) {
        throw e;
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        is.close();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    return sb.toString();
}