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.androidnerds.reader.util.api.Tags.java

/**
 * This method pulls the tags from Google Reader, its used by the 
 * methods in this class to communicate before parsing the specific
 * results./*w  ww. j  av  a 2 s. c  o m*/
 *
 * @param sid the Google Reader authentication string.
 * @return arr JSONArray of the items from the server.
 */
private static JSONArray pullTags(String sid) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(URL);
    BasicClientCookie cookie = Authentication.buildCookie(sid);

    try {
        client.getCookieStore().addCookie(cookie);

        HttpResponse response = client.execute(get);
        HttpEntity respEntity = response.getEntity();

        Log.d(TAG, "Response from server: " + response.getStatusLine());

        InputStream in = respEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line = "";
        String arr = "";
        while ((line = reader.readLine()) != null) {
            arr += line;
        }

        JSONObject obj = new JSONObject(arr);
        JSONArray array = obj.getJSONArray("tags");

        return array;
    } catch (Exception e) {
        Log.d(TAG, "Exception caught:: " + e.toString());
        return null;
    }
}

From source file:com.calclab.emite.core.client.services.android.AndroidConnector.java

public static void send(final String httpBase, final String request, final ConnectorCallback listener) {
    Runnable r = new Runnable() {
        public void run() {
            try {
                HttpPost method = new HttpPost(httpBase);
                method.addHeader("Content-Type", "text/xml; charset=\"utf-8\"");
                method.setEntity(new StringEntity(request, "utf-8"));

                final HttpResponse response = new DefaultHttpClient().execute(method);
                handler.post(new Runnable() {
                    public void run() {
                        try {
                            HttpEntity entity = response.getEntity();
                            String content = readInputStream(entity.getContent());
                            listener.onResponseReceived(response.getStatusLine().getStatusCode(), content);
                        } catch (Throwable e) {
                            listener.onError(request, e);
                        }//from  w  w w.j  a v  a 2s .  c o m
                    }
                });
            } catch (final Throwable e) {
                handler.post(new Runnable() {
                    public void run() {
                        listener.onError(request, e);
                    }
                });
            }
        }
    };
    new Thread(r).start();
}

From source file:monitor.console.control.HTTPRequest.java

public HTTPRequest(String login, byte[] password, FindUrl url)
        throws UnsupportedEncodingException, IOException {

    HttpClient client = new DefaultHttpClient();
    System.out.println(url.getHostName() + ":" + url.getPortNumber() + "/" + url.getRestServiceName());
    HttpPost post = new HttpPost(
            url.getHostName() + ":" + url.getPortNumber() + "/" + url.getRestServiceName());
    StringEntity input = new StringEntity(
            "{\"login\":" + "\"" + login + "\",\"password\":\"" + Arrays.toString(password) + "\"}");
    input.setContentType("application/json");
    post.setEntity(input);//from w w  w .j a v  a 2s . co m
    HttpResponse response = client.execute(post);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String tmp = "";
    while ((tmp = rd.readLine()) != null) {
        resp = tmp.replaceAll("\"", "");
        System.out.println(resp);
    }
}

From source file:eu.sisob.uma.NPL.Researchers.Freebase.Utils.java

public static JsonObject doRESTCall(String url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(url));

    JsonParser parser = new JsonParser();
    JsonObject json_data = (JsonObject) parser.parse(EntityUtils.toString(response.getEntity()));

    return json_data;
}

From source file:javafxapplication1.HttpClientExample.java

String sendGet(String url) throws Exception {

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);

    request.addHeader("User-Agent", USER_AGENT);

    HttpResponse response = client.execute(request);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);/*ww  w  .jav  a  2s  . c om*/
    }

    return result.toString();

}

From source file:org.trpr.platform.batch.impl.job.ha.service.FileUpload.java

/**
 * A generic method to execute any type of Http Request and constructs a response object
 * @param requestBase the request that needs to be exeuted
 * @return server response as <code>String</code>
 *//*w  ww  .j  av a 2  s .c  o m*/
public static String executeRequest(HttpRequestBase requestBase) {
    //The string holding the server response
    String responseString = "";
    InputStream responseStream = null;
    HttpClient client = new DefaultHttpClient();
    try {
        HttpResponse response = client.execute(requestBase);
        if (response != null) {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                responseStream = responseEntity.getContent();
                if (responseStream != null) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                    String responseLine = br.readLine();
                    String tempResponseString = "";
                    while (responseLine != null) {
                        tempResponseString = tempResponseString + responseLine
                                + System.getProperty("line.separator");
                        responseLine = br.readLine();
                    }
                    br.close();
                    if (tempResponseString.length() > 0) {
                        responseString = tempResponseString;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while uploading file to server", e);
    }
    client.getConnectionManager().shutdown();
    return responseString;
}

From source file:fr.eurecom.nerd.client.Request2.java

protected static synchronized String request(String uri, RequestType method,
        MultivaluedMap<String, String> queryParams) {
    HttpClient client = new DefaultHttpClient();

    //        System.out.println("TIMEOUTS= "+client.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT)+"    "+client.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT));
    //        client.setReadTimeout(timeout);
    //        client.setConnectTimeout(timeout);
    ///*from  w w w .jav  a2 s. c om*/
    //        System.out.println("TIMEOUTS= "+client.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT)+"    "+client.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT));

    //WebResource webResource = client.resource(uri);

    String json = null;

    List<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
    Iterator<String> paramsIterator = queryParams.keySet().iterator();

    switch (method) {
    case GET:

        while (paramsIterator.hasNext()) {
            String param = paramsIterator.next();
            List<String> listValues = queryParams.get(param);
            String value = "";
            for (int v = 0; v < listValues.size(); v++) {
                value = value + listValues.get(v);
                if (v + 1 != listValues.size())
                    value = value + ",";
            }
            BasicNameValuePair pair = new BasicNameValuePair(param, value);
            nameValuePairs.add(pair);
        }

        String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");

        uri = uri + paramString;
        HttpGet get = new HttpGet(uri);

        try {
            HttpResponse response = client.execute(get);

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

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

        /*            json = webResource.
                queryParams(queryParams).
                accept(MediaType.APPLICATION_JSON_TYPE).
                get(String.class);*/
        break;

    case POST:

        HttpPost post = new HttpPost(uri);
        try {

            while (paramsIterator.hasNext()) {
                String param = paramsIterator.next();
                List<String> listValues = queryParams.get(param);
                String value = "";
                for (int v = 0; v < listValues.size(); v++) {
                    value = value + listValues.get(v);
                    if (v + 1 != listValues.size())
                        value = value + ",";
                }
                BasicNameValuePair pair = new BasicNameValuePair(param, value);
                nameValuePairs.add(pair);
            }

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = client.execute(post);

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

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

        /*            
                    json = webResource.
                accept(MediaType.APPLICATION_JSON_TYPE). 
                post(String.class, queryParams);
                    break;*/

    default:
        break;
    }

    return json;
}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(nuts.urlString());
    System.out.println("NUTS" + nuts.toString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            httppost.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }/*from w  w w. j a v  a  2s . c  om*/
    }
    if (nuts.fileEntity() != null) {
        httppost.setEntity(nuts.fileEntity());
    }
    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }
    TransportResponse transportResp = null;
    System.out.println(httppost.toString());
    try {
        HttpResponse httpResp = httpclient.execute(httppost);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httppost.releaseConnection();
    }
    return transportResp;

}

From source file:Services.Leer.java

public JSONArray leer(String ruta) throws ClientProtocolException, IOException, JSONException {

    HttpClient client = new DefaultHttpClient();
    int id = 1;/*from   w ww . j  av  a  2 s  . co m*/
    // HttpGet get = new HttpGet("http://ip.no-ip.org:8000/ruta");
    HttpGet get = new HttpGet(ruta);

    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    String content = EntityUtils.toString(entity);
    System.out.println("ESTE ES EL JSON en LEER " + content);

    JSONArray json = new JSONArray(content);

    return json;
}

From source file:eu.scape_project.fcrepo.integration.AbstractIT.java

@BeforeClass
public static void init() throws Exception {
    /* wait for an existing ContainerWrapper to finish */
    try {//  w w  w .j  a  v  a  2  s  .  com
        HttpGet get = new HttpGet("http://localhost:8080");
        DefaultHttpClient client = new DefaultHttpClient();
        while (client.execute(get).getStatusLine().getStatusCode() > 0) {
            Thread.sleep(1000);
            System.out.println("Waiting for existing application server to stop...");
        }
    } catch (ConnectException e) {
        // it's good, we can't connect to 8080
        // don't do exec flow by exception handling though ;)
    }
}