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:Main.java

/**
 * Make POST request and return plain response
 * @param url/*from   w w w.j  a  va  2 s.  c  om*/
 * @param pairs
 * @return Plain text response
 * @throws Exception
 */
public static String makeHttpPostRequest(String url, List<NameValuePair> pairs) throws Exception {
    BufferedReader in = null;
    String result = "";
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        result = sb.toString();
        // System.out.println(result);
    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return result;
}

From source file:com.yattatech.gcm.gui.GCMSender.java

public static void send(String channel, String message, String classKey) throws Exception {

    loadProperties();//from   w  w w  .  j a va2 s .c om
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpPost httpPost = new HttpPost("https://android.googleapis.com/gcm/send");
    final Class<?> formatClass = Class.forName(PROPERTIES.getProperty(classKey));
    final RequestFormat format = (RequestFormat) formatClass.newInstance();
    //HttpHost proxy    = new HttpHost(PROPERTIES.getProperty("proxy.host"), Integer.parseInt(PROPERTIES.getProperty("proxy.port")));                  
    //httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);      
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Authorization", PROPERTIES.getProperty("auth.key"));
    httpPost.setEntity(format.getRequest(channel, message));
    HttpResponse response = httpClient.execute(httpPost);
    final String content = IOUtils.toString(response.getEntity().getContent());
    System.out.println("Response status " + response.getStatusLine().getStatusCode());
    if (logCallback != null) {
        logCallback.message(content);
    }
    System.out.println("Response " + content);
}

From source file:Main.java

public static String makeRequest1(String url, String json) {
    Log.v(TAG, "URL-->" + url);
    Log.v(TAG, "input-->" + json);

    try {//  w ww  . ja  va  2 s.co m
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(json));

        HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);

        // receive response as inputStream
        InputStream inputStream = httpResponse.getEntity().getContent();
        // convert inputstream to string
        if (inputStream != null) {
            String result = convertInputStreamToString(inputStream);
            Log.v(TAG, "output-->" + result);
            return result;
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

From source file:Extras.JSON.java

public static HttpResponse request(String URL, List parametros) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);
    HttpResponse response = null;//  www.j  a va2 s.c om
    try {
        httppost.setEntity(new UrlEncodedFormEntity(parametros));
        response = httpclient.execute(httppost);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    return response;
}

From source file:Main.java

static public String doHttpGet(String url, HashMap<String, String> map) {

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
    HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
    ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
    String result = "ERROR";
    if (null != map) {
        int i = 0;
        for (Map.Entry<String, String> entry : map.entrySet()) {

            if (i == 0) {
                url = url + "?" + entry.getKey() + "=" + entry.getValue();
            } else {
                url = url + "&" + entry.getKey() + "=" + entry.getValue();
            }/*w  w w.  j  a  v a2  s.c om*/

            i++;

        }
    }
    HttpGet get = new HttpGet(url);
    get.setHeaders(headers);
    try {

        HttpResponse response = client.execute(get);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // setCookie(response);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");

        } else {
            result = EntityUtils.toString(response.getEntity(), "UTF-8")
                    + response.getStatusLine().getStatusCode() + "ERROR";
        }
        if (result != null) {
            if (result.startsWith("\ufeff")) {
                result = result.substring(1);
            }
        }

    } catch (ConnectTimeoutException e) {
        result = "TIMEOUTERROR";
    }

    catch (Exception e) {
        result = "OTHERERROR";
        e.printStackTrace();

    }

    return result;
}

From source file:Main.java

public static String httpStringGet(String url, String enc) throws Exception {
    // This method for HttpConnection
    String page = "";
    BufferedReader bufferedReader = null;
    try {// w  ww.ja  v a 2 s . c o  m
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");

        HttpParams httpParams = client.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
        HttpConnectionParams.setSoTimeout(httpParams, 5000);

        HttpGet request = new HttpGet();
        request.setHeader("Content-Type", "text/plain; charset=utf-8");
        request.setURI(new URI(url));
        HttpResponse response = client.execute(request);
        bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), enc));

        StringBuffer stringBuffer = new StringBuffer("");
        String line = "";

        String NL = System.getProperty("line.separator");// "\n"
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line + NL);
        }
        bufferedReader.close();
        page = stringBuffer.toString();
        Log.i("page", page);
        System.out.println(page + "page");
        return page;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                Log.d("BBB", e.toString());
            }
        }
    }
}

From source file:com.devdungeon.httpexamples.HttpGetExample.java

private static String get(String url) {
    HttpClient client = new DefaultHttpClient();

    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 1000 * 5);
    HttpConnectionParams.setSoTimeout(params, 1000 * 5);

    HttpGet request = new HttpGet(url);

    HttpResponse response = null;/*from  ww w .j ava  2 s. c  o m*/
    try {
        response = client.execute(request);
    } catch (IOException ex) {
        Logger.getLogger(HttpGetExample.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedReader rd;
    String html = "";
    String line = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        while ((line = rd.readLine()) != null) {
            html += line + "\n";

        }
    } catch (IOException ex) {
        Logger.getLogger(HttpGetExample.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedOperationException ex) {
        Logger.getLogger(HttpGetExample.class.getName()).log(Level.SEVERE, null, ex);
    }
    return html;
}

From source file:eu.dime.userresolver.client.utils.HttpUtils.java

public static DefaultHttpClient createHttpClient() {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if ((proxyHost != null) && (proxyPort != null)) {
        HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }//from   w ww .  ja  v a 2 s  .com

    return httpClient;

}

From source file:Technique.PostFile.java

public static void upload(String files) throws Exception {

    String userHome = System.getProperty("user.home");
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost("http://localhost/image/up.php");
    File file = new File(files);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody contentFile = new FileBody(file);
    mpEntity.addPart("userfile", contentFile);
    httppost.setEntity(mpEntity);/*from   ww w . j  a  v a 2  s. c  o m*/
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (!(response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")) {
        // Successfully Uploaded
    } else {
        // Did not upload. Add your logic here. Maybe you want to retry.
    }
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
        System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
}

From source file:brokerja.Worker.java

public static Document getDoc(String root) {

    HttpClient client = new DefaultHttpClient();
    Document doc = null;/*from  www .  java  2 s.c  o m*/
    try {
        while (doc == null) {
            HttpGet request = new HttpGet(root);

            request.setHeader("User-Agent", USER_AGENT);
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            request.setHeader("Accept-Language", "en-US,en;q=0.5");
            HttpResponse response = client.execute(request);
            //
            //                System.out.println("Response Code : "
            //                        + response.getStatusLine().getStatusCode());

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

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            doc = Jsoup.parse(result.toString());
        }
    } catch (SocketTimeoutException e) {
        //ERROR TYPE 1
        System.out.println("Socket Timeout Error");
        System.out.println(e);
        System.exit(0);
    } catch (SocketException e) {
        //ERROR TYPE 1
        System.out.println("Internet Connection Error");
        System.out.println(e);
        System.exit(0);
    } catch (Exception e) {
        //ERROR TYPE 2
        System.out.println("JSoup Error");
        System.out.println(e);
        System.exit(0);
    }
    return doc;
}