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(final HttpParams params) 

Source Link

Usage

From source file:com.core.ServerConnector.java

public static String post(String endpoint, Map<String, String> params) throws Exception {
    String result = null;/*  ww  w  . j ava2s.co m*/
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(endpoint);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        nameValuePairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
    }
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        result = SystemUtil.convertStreamToString(instream);

        instream.close();
    }

    return result;
}

From source file:be.uclouvain.multipathcontrol.stats.HttpUtils.java

public static HttpClient getHttpClient(int timeout) {
    if (ConfigServer.hostname.isEmpty())
        return null;

    DefaultHttpClient defaultHttpClient;
    if (timeout > 0)
        defaultHttpClient = new DefaultHttpClient(getParamTimeout(timeout));
    else/* w  w w. ja  v  a  2 s.  com*/
        defaultHttpClient = new DefaultHttpClient();
    if (ConfigServer.username != null && !ConfigServer.username.isEmpty()) {
        Credentials creds = new UsernamePasswordCredentials(ConfigServer.username, ConfigServer.password);
        AuthScope scope = new AuthScope(ConfigServer.hostname, ConfigServer.port);
        CredentialsProvider credProvider = defaultHttpClient.getCredentialsProvider();
        credProvider.setCredentials(scope, creds);
    }
    return defaultHttpClient;
}

From source file:wuit.common.crawler.search.Crawler.java

public static String doGetHttp(String url) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 12000);
    HttpConnectionParams.setSoTimeout(params, 9000);
    HttpClient httpclient = new DefaultHttpClient(params);
    String rs = "";
    try {/*from  w ww .  j a va  2s .  co  m*/
        //            System.out.println(url);
        HttpGet httpget = new HttpGet(url);

        HttpContext httpContext = new BasicHttpContext();
        //            httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        httpget.addHeader("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");

        HttpResponse response = httpclient.execute(httpget, httpContext);
        HttpUriRequest realRequest = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        url = targetHost.toString() + realRequest.getURI();
        int resStatu = response.getStatusLine().getStatusCode();//? 
        if (resStatu == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                rs = EntityUtils.toString(entity, "iso-8859-1");
                String in_code = getEncoding(rs);
                String encode = getHtmlEncode(rs);
                if (encode.isEmpty()) {
                    httpclient.getConnectionManager().shutdown();
                    return "";
                } else {
                    if (!in_code.toLowerCase().equals("utf-8")
                            && !in_code.toLowerCase().equals(encode.toLowerCase())) {
                        if (!in_code.toLowerCase().equals("iso-8859-1"))
                            rs = new String(rs.getBytes("iso-8859-1"), in_code);
                        if (!encode.toLowerCase().equals(in_code.toLowerCase()))
                            rs = new String(rs.getBytes(in_code), encode);
                    }
                }
                try {
                } catch (RuntimeException ex) {
                    httpget.abort();
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    //                    try { instream.close(); } catch (Exception ignore) {}
                }
            }
        }
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
        return rs;
    }
}

From source file:com.blacklocus.sample.time.HttpClientFactory.java

/**
 * Construct a new HttpClient which uses the {@link #POOL_MGR default connection pool}.
 *
 * @param connectionTimeout highly sensitive to application so must be specified
 * @param socketTimeout highly sensitive to application so must be specified
 *//* w  w  w .  ja va 2 s  .com*/
public static HttpClient createHttpClient(final int connectionTimeout, final int socketTimeout) {
    return new DefaultHttpClient(POOL_MGR) {
        {
            HttpParams httpParams = getParams();

            // prevent seg fault JVM bug, see https://code.google.com/p/crawler4j/issues/detail?id=136
            httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

            HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
            HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
            HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);

        }
    };
}

From source file:edu.scripps.fl.pubchem.web.session.HttpClientBase.java

public HttpClientBase() {
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    cm.setMaxTotal(100);
    client = new DefaultHttpClient(cm);
}

From source file:com.rackspacecloud.blueflood.http.HttpClientVendor.java

public HttpClientVendor() {
    client = new DefaultHttpClient(buildConnectionManager(20));
    client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
    client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);

    // Wait this long for an available connection. Setting this correctly is important in order to avoid
    // connectionpool timeouts.
    client.getParams().setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 5000);
}

From source file:org.zywx.wbpalmstar.engine.eservice.EServiceTest.java

public static void test() {
    String realyPath = "http://localhost:8000/other.QDV";
    HttpRequestBase mHhttpRequest = new HttpGet(realyPath);
    mHhttpRequest.addHeader("range", "bytes=34199-");
    BasicHttpParams bparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(bparams, 20000);
    HttpConnectionParams.setSoTimeout(bparams, 20000);
    HttpConnectionParams.setSocketBufferSize(bparams, 8 * 1024);
    HttpClientParams.setRedirecting(bparams, true);
    DefaultHttpClient mDefaultHttpClient = new DefaultHttpClient(bparams);
    HttpResponse response = null;/*  w w  w . jav a 2 s  .c  o m*/
    try {
        response = mDefaultHttpClient.execute(mHhttpRequest);

        int responseCode = response.getStatusLine().getStatusCode();
        byte[] arrayOfByte = null;
        HttpEntity httpEntity = response.getEntity();
        if (responseCode == 200 || responseCode == 206) {
            arrayOfByte = toByteArray(httpEntity);
            String m = new String(arrayOfByte, "UTF-8");
            Log.i("ldx", "" + m.length());
            Log.i("ldx", m);
            return;

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

From source file:com.jesjimher.bicipalma.BicipalmaJsonClient.java

public static JSONArray connect(String url) {

    JSONArray json = new JSONArray();

    try {/*from   w  w w.ja  v a 2 s . com*/
        // 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;
}