Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getParams.

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:com.traffic.common.utils.http.HttpClientUtils.java

/**
 * map? post//from   ww  w.  ja va 2  s  . com
 * @param url
 * @param mapParam
 * @return
 */
public static String httpPost_JSONObject(String url, JSONObject reqParam) {
    logger.debug("httpPost URL [" + url + "] start ");
    logger.debug("httpPost param :" + reqParam.toJSONString());
    HttpClient httpclient = null;
    HttpPost httpPost = null;
    HttpResponse response = null;
    HttpEntity entity = null;
    String result = "";

    try {
        //         httpclient = HttpConnectionManager.getHttpClient();
        httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        httpPost = new HttpPost(url);
        // ???
        for (Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }

        // ?    
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (String key : reqParam.keySet()) {
            formparams.add(new BasicNameValuePair(key, (String) reqParam.get(key)));
        }
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httpPost.setEntity(uefEntity);

        // 
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 40000);
        // ?
        HttpConnectionParams.setSoTimeout(httpPost.getParams(), 200000);
        response = httpclient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("HttpStatus ERROR" + "Method failed: " + response.getStatusLine());
            return "";
        } else {
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, "UTF-8");
            } else {
                logger.error("httpPost URL [" + url + "],httpEntity is null.");
            }
            logger.debug("httpPost response:" + result);
            return result;
        }
    } catch (Exception e) {
        logger.error("httpPost URL [" + url + "] error, ", e);
        return "";
    }
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method,
        String xml) {/*w  w w .ja  v  a 2  s  .c o m*/

    String reqURL = "https://" + ip + ":" + port + action;
    //      Map<String, String> params = null;
    long responseLength = 0; // ?
    String responseContent = null; // ?

    HttpClient httpClient = new DefaultHttpClient(); // httpClient
    httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    X509TrustManager xtm = new X509TrustManager() { // TrustManager
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        // TLS1.0SSL3.0??TLSSSL?SSLContext
        SSLContext ctx = SSLContext.getInstance("TLS");

        // TrustManager??TrustManager?SSLSocket
        ctx.init(null, new TrustManager[] { xtm }, null);

        // SSLSocketFactory
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

        // SchemeRegistrySSLSocketFactoryHttpClient
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", port, socketFactory));

        HttpPost httpPost = new HttpPost(reqURL); // HttpPost

        // add the 3 headers below
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
        httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        httpPost.addHeader("uuid", "itest");// for editor token of DR-Api

        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8
        httpPost.setEntity(requestBody);
        log.info(">> Request URI: " + httpPost.getRequestLine().getUri());

        HttpResponse response = httpClient.execute(httpPost); // POST
        HttpEntity entity = response.getEntity(); // ??

        if (null != entity) {
            responseLength = entity.getContentLength();

            String contentEncoding = null;
            Header ce = response.getEntity().getContentEncoding();
            if (ce != null) {
                contentEncoding = ce.getValue();
            }

            if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
                GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
                Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                while (in.hasNextLine()) {
                    sb.append(in.nextLine()).append(System.getProperty("line.separator"));
                }
                responseContent = sb.toString();
            } else {
                responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

            EntityUtils.consume(entity); // Consume response content
        }
        log.info("?: " + httpPost.getURI());
        log.info("??: " + response.getStatusLine());
        log.info("?: " + responseLength);
        log.info("?: " + responseContent);
    } catch (KeyManagementException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        log.error(e.getMessage(), e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown(); // ,?
        return responseContent;
    }
}

From source file:cn.tc.ulife.platform.msg.http.util.HttpUtil.java

/**
 * HTTP POST?//  w w w .j a  va  2 s  . com
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers,
        Map<String, String> querys, Map<String, String> bodys, List<String> signHeaderPrefixList, String appKey,
        String appSecret) throws Exception {
    if (headers == null) {
        headers = new HashMap<String, String>();
    }

    headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_FORM);

    headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, bodys, signHeaderPrefixList, appKey,
            appSecret);

    HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPost post = new HttpPost(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    UrlEncodedFormEntity formEntity = buildFormEntity(bodys);
    if (formEntity != null) {
        post.setEntity(formEntity);
    }

    return convert(httpClient.execute(post));
}

From source file:com.svo.library.widget.RLWebBrowser.java

/**
* get?url???.?. HttpClientgzip// ww  w  . ja va 2 s .  co m
* 
* @param strUrl url?
* @return ?? null
*/
public static String getRequest(String strUrl) {
    HttpClient client = new DefaultHttpClient();
    HttpParams httpParams = client.getParams();
    String result = null; // 
    try {
        HttpGet get = new HttpGet(strUrl);
        // ?
        HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
        HttpConnectionParams.setSoTimeout(httpParams, 30000);
        HttpResponse response = client.execute(get);

        int statusCode = response.getStatusLine().getStatusCode(); // ?
        if (statusCode == 200) {
            result = EntityUtils.toString(response.getEntity(), "gbk");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends a {@link MultipartEntity} post with text and image files.
 * /*from www. ja v  a 2  s . c  o m*/
 * @param url the url to which to POST to.
 * @param user the user or <code>null</code>.
 * @param pwd the password or <code>null</code>.
 * @param stringsMap the {@link HashMap} containing the key and string pairs to send.
 * @param filesMap the {@link HashMap} containing the key and image file paths 
 *                  (jpg, png supported) pairs to send.
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap,
        HashMap<String, File> filesMap)
        throws UnsupportedEncodingException, IOException, ClientProtocolException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(url);

    if (user != null && pwd != null) {
        String ret = getB64Auth(user, pwd);
        httppost.setHeader("Authorization", ret);
    }

    MultipartEntity mpEntity = new MultipartEntity();
    Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet();
    for (Entry<String, String> stringEntry : stringsEntrySet) {
        ContentBody cbProperties = new StringBody(stringEntry.getValue());
        mpEntity.addPart(stringEntry.getKey(), cbProperties);
    }

    Set<Entry<String, File>> filesEntrySet = filesMap.entrySet();
    for (Entry<String, File> filesEntry : filesEntrySet) {
        String propName = filesEntry.getKey();
        File file = filesEntry.getValue();
        if (file.exists()) {
            String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png";
            ContentBody cbFile = new FileBody(file, "image/" + ext);
            mpEntity.addPart(propName, cbFile);
        }
    }

    httppost.setEntity(mpEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
}

From source file:org.thoughtcrime.securesms.mms.MmsSendHelper.java

private static byte[] makePost(MmsConnectionParameters parameters, byte[] mms)
        throws ClientProtocolException, IOException {
    Log.w("MmsSender", "Sending MMS1 of length: " + mms.length);
    try {//from w  ww.  j a  v  a 2 s.  c om
        HttpClient client = constructHttpClient(parameters);
        URI hostUrl = new URI(parameters.getMmsc());
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpPost request = new HttpPost(parameters.getMmsc());
        ByteArrayEntity entity = new ByteArrayEntity(mms);

        entity.setContentType("application/vnd.wap.mms-message");

        request.setEntity(entity);
        request.setParams(client.getParams());
        request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        HttpResponse response = client.execute(target, request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());

        return parseResponse(response.getEntity());
    } catch (URISyntaxException use) {
        Log.w("MmsDownlader", use);
        throw new IOException("Bad URI syntax");
    }
}

From source file:com.dubsar_dictionary.Dubsar.model.Model.java

private static HttpClient newClient() {
    String userAgent = getString(R.string.user_agent);
    userAgent += " ("
            + getContext().getString(R.string.android_version, new Object[] { Build.VERSION.RELEASE });
    userAgent += "; " + getContext().getString(R.string.build, new Object[] { Build.DISPLAY });
    userAgent += ")";

    HttpClient client = AndroidHttpClient.newInstance(userAgent, getContext());
    HttpClientParams.setRedirecting(client.getParams(), true);

    return client;
}

From source file:it.restrung.rest.client.DefaultRestClientImpl.java

/**
 * Private helper to setup the request timeout
 */// w ww.ja v a  2  s  .  c  o  m
private static void setupTimeout(int timeout, HttpClient client) {
    if (timeout > 0) {
        HttpConnectionParams.setConnectionTimeout(client.getParams(), timeout);
    }
}

From source file:com.ljt.openapi.demo.util.HttpUtil.java

/**
 * HTTP GET// ww w.  j  a v a  2s  . co  m
 * 
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpGet(String host, String path, int connectTimeout, Map<String, String> headers,
        Map<String, String> querys, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
    headers = initialBasicHeader(HttpMethod.GET, path, headers, querys, null, signHeaderPrefixList, appKey,
            appSecret);

    HttpClient httpClient = wrapClient(host);

    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpGet get = new HttpGet(initUrl(host, path, querys));

    for (Map.Entry<String, String> e : headers.entrySet()) {
        get.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    return convert(httpClient.execute(get));
}

From source file:com.ljt.openapi.demo.util.HttpUtil.java

/**
 * HTTP POST?//from   w w w.  j a va2s .  c  o  m
 * 
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers,
        Map<String, String> querys, Map<String, String> bodys, List<String> signHeaderPrefixList, String appKey,
        String appSecret) throws Exception {
    if (headers == null) {
        headers = new HashMap<String, String>();
    }

    headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_FORM);

    headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, bodys, signHeaderPrefixList, appKey,
            appSecret);

    HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPost post = new HttpPost(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    UrlEncodedFormEntity formEntity = buildFormEntity(bodys);
    if (formEntity != null) {
        post.setEntity(formEntity);
    }
    return convert(httpClient.execute(post));
}