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:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonNode postToServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;//from ww w.  j a v a  2 s . c  o  m
    LOG.d("POST api request, url = " + urlString + " object = " + objectToPost.toString());
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT);
    HttpPost httppost = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httppost = new HttpPost(url.toString());
        httppost.setHeader("Content-type", "application/json");
        httppost.setHeader("Accept", ACCEPT);
        httppost.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);// , HTTP.UTF_8
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("API response = " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null) {
            LOG.e(e.getLocalizedMessage());
        }
    }
    return ret;
}

From source file:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonNode putToServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;//from  w w w.  ja  v a2s. co m
    LOG.d("PUT api request, url = " + urlString);
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT);
    HttpPut httput = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httput = new HttpPut(url.toString());
        httput.setHeader("Content-type", "application/json");
        httput.setHeader("Accept", ACCEPT);
        httput.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httput.setEntity(se);
        HttpResponse response = httpclient.execute(httput);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("API response = " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null) {
            LOG.e(e.getLocalizedMessage());
        }
    }
    return ret;
}

From source file:org.eclipse.epp.internal.mpc.core.util.HttpUtil.java

public static void configureProxy(HttpClient client, String url) {
    final IProxyData proxyData = ProxyHelper.getProxyData(url);
    if (proxyData != null && !IProxyData.SOCKS_PROXY_TYPE.equals(proxyData.getType())) {
        HttpHost proxy = new HttpHost(proxyData.getHost(), proxyData.getPort(),
                proxyData.getType().toLowerCase());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (proxyData.isRequiresAuthentication()) {
            ((AbstractHttpClient) client).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyData.getHost(), proxyData.getPort()),
                    new UsernamePasswordCredentials(proxyData.getUserId(), proxyData.getPassword()));
        }/*w ww.  ja va2  s . c om*/
    }
}

From source file:org.linkdroid.PostJob.java

/**
 * Posts the data to our webhook./*  ww  w.j ava2 s.  c  om*/
 * 
 * The HMAC field calculation notes:
 * <ol>
 * <li>The Extras.HMAC field is calculated from all the non Extras.STREAM
 * fields; this includes all the original bundle extra fields, plus the
 * linkdroid fields (e.g Extras.STREAM_MIME_TYPE, and including
 * Extras.STREAM_HMAC); the NONCE is NOT prepended to the input since it will
 * be somewhere in the data bundle.</li>
 * <li>The Extras.STREAM_HMAC field is calculated by digesting the concat of
 * the NONCE (first) and the actual binary data obtained from the
 * EXTRAS_STREAM uri; this STREAM_HMAC field (along with the other
 * Extras.STREAM_* fields) are added to the data bundle, which will also be
 * hmac'd.</li>
 * <li>If no hmac secret is set, then the NONCEs will not be set in the upload
 * </li>
 * </ol>
 * 
 * @param contentResolver
 * @param webhook
 * @param data
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 */
public static void execute(ContentResolver contentResolver, Bundle webhook, Bundle data)
        throws UnsupportedEncodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {

    // Set constants that may be used in this method.
    final String secret = webhook.getString(WebhookColumns.SECRET);

    // This is the multipart form object that will contain all the data bundle
    // extras; it also will include the data of the extra stream and any other
    // extra linkdroid specific field required.
    MultipartEntity entity = new MultipartEntity();

    // Do the calculations to create our nonce string, if necessary.
    String nonce = obtainNonce(webhook);

    // Add the nonce to the data bundle if we have it.
    if (nonce != null) {
        data.putString(Extras.NONCE, nonce);
    }

    // We have a stream of data, so we need to add that to the multipart form
    // upload with a possible HMAC.
    if (data.containsKey(Intent.EXTRA_STREAM)) {
        Uri mediaUri = (Uri) data.get(Intent.EXTRA_STREAM);

        // Open our mediaUri, base 64 encode it and add it to our multipart upload
        // entity.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream b64os = new Base64OutputStream(baos);
        InputStream is = contentResolver.openInputStream(mediaUri);
        byte[] bytes = new byte[1024];
        int count;
        while ((count = is.read(bytes)) != -1) {
            b64os.write(bytes, 0, count);
        }
        is.close();
        baos.close();
        b64os.close();
        final String base64EncodedString = new String(baos.toByteArray(), UTF8);
        entity.addPart(Extras.STREAM, new StringBody(base64EncodedString, UTF8_CHARSET));

        // Add the mimetype of the stream to the data bundle.
        final String mimeType = contentResolver.getType(mediaUri);
        if (mimeType != null) {
            data.putString(Extras.STREAM_MIME_TYPE, mimeType);
        }

        // Do the hmac calculation of the stream and add it to the data bundle.
        // NOTE: This hmac string will be included as part of the input to the
        // other Extras hmac.
        if (shouldDoHmac(webhook)) {
            InputStream inputStream = contentResolver.openInputStream(mediaUri);
            final String streamHmac = hmacSha1(inputStream, secret, nonce);
            inputStream.close();
            data.putString(Extras.STREAM_HMAC, streamHmac);
            Log.d(TAG, "STREAM_HMAC: " + streamHmac);
        }
    }

    // Calculate the Hmac for all the items by iterating over the data bundle
    // keys in order.
    if (shouldDoHmac(webhook)) {
        final String dataHmac = calculateBundleExtrasHmac(data, secret);
        data.putString(Extras.HMAC, dataHmac);
        Log.d(TAG, "HMAC: " + dataHmac);
    }

    // Dump all the data bundle keys into the form.
    for (String k : data.keySet()) {
        Object value = data.get(k);
        // If the value is null, the key will still be in the form, but with
        // an empty string as its value.
        if (value != null) {
            entity.addPart(k, new StringBody(value.toString(), UTF8_CHARSET));
        } else {
            entity.addPart(k, new StringBody("", UTF8_CHARSET));
        }
    }

    // Create the client and request, then populate it with our multipart form
    // upload entity as part of the POST request; finally post the form.
    final String webhookUri = webhook.getString(WebhookColumns.URI);
    final HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(USER_AGENT_KEY, USER_AGENT);
    final HttpPost request = new HttpPost(webhookUri);
    request.setEntity(entity);
    HttpResponse response = client.execute(request);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
        break;
    default:
        throw new RuntimeException(response.getStatusLine().toString());
    }
}

From source file:org.ofbiz.party.tool.SmsSimpleClient.java

/**
 * ??http GEThttp?//from  w  w w .j ava2s . c om
 * 
 * @param urlstr url
 * @return
 */
public static String doGetRequest(String urlstr) {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setIntParameter("http.socket.timeout", 10000);
    client.getParams().setIntParameter("http.connection.timeout", 5000);

    HttpEntity entity = null;
    String entityContent = null;
    try {
        HttpGet httpGet = new HttpGet(urlstr.toString());

        HttpResponse httpResponse = client.execute(httpGet);
        entityContent = EntityUtils.toString(httpResponse.getEntity());

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (Exception e) {
                Debug.logError(e, module);
            }
        }
    }
    return entityContent;
}

From source file:com.example.aliyundemo.ocr.util.HttpUtil.java

/**
 * Http POST /*from   w  w  w .  j ava2 s  .com*/
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param body                 
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpPost(String url, Map<String, String> headers, String body, String appKey,
        String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.POST, url, null, signHeaderPrefixList);
    //HttpClient httpClient = new DefaultHttpClient();
    HttpClient httpClient = new SSLClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

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

    if (StringUtils.isNotBlank(body)) {
        post.setEntity(new StringEntity(body, Constants.ENCODING));

    }

    return httpClient.execute(post);
}

From source file:org.bfr.querytools.google.GoogleSpectrumQuery.java

public static void query(double latitude, double longitude) {

    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost("https://www.googleapis.com/rpc");
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10 * 1000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 10 * 1000);

    request.addHeader("Content-Type", "application/json");

    try {//from  w ww .  j  a  va  2  s .  co  m
        request.setEntity(new StringEntity(createQuery(latitude, longitude).toString(), HTTP.UTF_8));

        Logger.log(String.format("google-query-execute %.4f %.4f", latitude, longitude));

        HttpResponse response = client.execute(request);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        boolean first = true;
        while ((line = rd.readLine()) != null) {
            if (first) {
                Logger.log("google-query-first-data");
                first = false;
            }
            Logger.log(line);
        }

    } catch (UnsupportedEncodingException e) {
        Logger.log("google-query-error Unsupported Encoding: " + e.getMessage());
    } catch (JSONException e) {
        Logger.log("google-query-error JSON exception: " + e.getMessage());
    } catch (IOException e) {
        Logger.log("google-query-error i/o exception: " + e.getMessage());
    }

    Logger.log("google-query-done");

}

From source file:org.ofbiz.party.tool.SmsSimpleClient.java

/**
 * ??http POSThttp?/*from  w w  w  .  j  a  v  a 2 s .  c o  m*/
 * 
 * @param urlstr url
 * @return
 */
public static String doPostRequest(String urlstr, HashMap<String, String> content) {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setIntParameter("http.socket.timeout", 10000);
    client.getParams().setIntParameter("http.connection.timeout", 5000);
    List<NameValuePair> ls = new ArrayList<NameValuePair>();
    for (String key : content.keySet()) {
        NameValuePair param = new BasicNameValuePair(key, content.get(key));
        ls.add(param);
    }
    HttpEntity entity = null;
    String entityContent = null;
    try {
        HttpPost httpPost = new HttpPost(urlstr.toString());
        UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(ls, "UTF-8");
        httpPost.setEntity(uefe);

        HttpResponse httpResponse = client.execute(httpPost);
        entityContent = EntityUtils.toString(httpResponse.getEntity());

    } catch (Exception e) {
        Debug.logError(e, module);
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (Exception e) {
                Debug.logError(e, module);
            }
        }
    }
    return entityContent;
}

From source file:com.example.aliyundemo.ocr.util.HttpUtil.java

/**
 * HTTP DELETE/*  w  w w  .j a  v a2 s .  c  o m*/
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpDelete(String url, Map<String, String> headers, String appKey, String appSecret,
        int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.DELETE, url, null,
            signHeaderPrefixList);
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

    HttpDelete delete = new HttpDelete(url);
    for (Map.Entry<String, String> e : headers.entrySet()) {
        delete.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    return httpClient.execute(delete);
}

From source file:com.example.aliyundemo.ocr.util.HttpUtil.java

/**
 * HTTP GET/*from   w  ww  . j av  a2s  . co  m*/
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpGet(String url, Map<String, String> headers, String appKey, String appSecret,
        int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.GET, url, null, signHeaderPrefixList);

    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

    HttpGet get = new HttpGet(url);

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

    return httpClient.execute(get);
}