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.example.caique.educam.Activities.TimelineActivity.java

private JSONObject POST(JSONObject rawJson) throws IOException, ParseException, JSONException {
    JSONObject json = rawJson;//from  w w w  .  j  a  v  a 2s  .  c  om

    Log.e(getLocalClassName(), "JSON IN: " + json);
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

    JSONObject jsonResponse = null;
    HttpPost post = null;
    switch (rawJson.getString("type")) {
    case "ALL":
        post = new HttpPost(Constants.MAIN_URL + "post/all");
        break;
    }

    try {
        StringEntity se = new StringEntity("json=" + json.toString());
        post.addHeader("content-type", "application/x-www-form-urlencoded");
        post.setEntity(se);

        HttpResponse response;
        response = client.execute(post);
        String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
        Log.e("Response: ", resFromServer);

        jsonResponse = new JSONObject(resFromServer);
        Log.e("Response from server: ", jsonResponse.getString("status") + jsonResponse.getJSONArray("posts"));
        return jsonResponse;

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

From source file:com.careerly.utils.HttpClientUtils.java

/**
 * ??https//from ww w.j av a 2  s  . c  o m
 *
 * @param base
 * @return
 */
private static HttpClient wrapHttpsClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 443, ssf));
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
        return new DefaultHttpClient(mgr, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:HttpsRequestDemo.java

private String sentHttpPostRequest(String requestMsg) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();

    // SSLSocketFactory
    registerSSLSocketFactory(httpclient);

    // //from  w  ww . ja v a 2s. c o m
    int timeout = 60000;
    HttpConnectionParams.setSoTimeout(httpclient.getParams(), timeout);

    // post
    HttpPost httppost = new HttpPost(targetURL);

    // 
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // 
    params.add(new BasicNameValuePair("messageRouter", messageRouter));
    // 
    params.add(new BasicNameValuePair("tradingPartner", partnerCode));
    // 
    params.add(new BasicNameValuePair("documentProtocol", documentProtocol));
    // xml
    params.add(new BasicNameValuePair("requestMessage", requestMsg));

    // UTF-8
    HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");
    httppost.setEntity(request);

    // xmlxml
    HttpResponse httpResponse = httpclient.execute(httppost);
    HttpEntity entity = httpResponse.getEntity();
    String result = null;
    if (entity != null) {
        result = EntityUtils.toString(entity);
    }

    return result;
}

From source file:org.n52.sir.client.Client.java

/**
 * @param request//from  w  w w  .j  av a 2 s .  com
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws HttpException
 * @throws OwsExceptionReport
 */
private XmlObject doSend(String request, String requestMethod, URI uri)
        throws UnsupportedEncodingException, IOException, HttpException, OwsExceptionReport {
    if (log.isDebugEnabled())
        log.debug("Sending request (first 100 characters): "
                + request.substring(0, Math.min(request.length(), 100)));

    HttpClient client = new DefaultHttpClient();
    // configure timeout to handle really slow servers
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);

    HttpRequestBase method = null;

    if (requestMethod.equals(GET_METHOD)) {
        log.debug("Client connecting via GET to '{}' with request '{}'", uri, request);

        String fullUri = null;
        if (request == null || request.isEmpty())
            fullUri = uri.toString();
        else
            fullUri = uri.toString() + "?" + request;

        log.debug("GET call: {}", fullUri);
        HttpGet get = new HttpGet(fullUri);
        method = get;
    } else if (requestMethod.equals(POST_METHOD)) {
        if (log.isDebugEnabled())
            log.debug("Client connecting via POST to " + uri);
        HttpPost postMethod = new HttpPost(uri.toString());

        postMethod.setEntity(new StringEntity(request, ContentType.create(SirConstants.REQUEST_CONTENT_TYPE)));

        method = postMethod;
    } else {
        throw new IllegalArgumentException("requestMethod not supported!");
    }

    try {
        HttpResponse httpResponse = client.execute(method);

        try (InputStream is = httpResponse.getEntity().getContent();) {
            XmlObject responseObject = XmlObject.Factory.parse(is);
            return responseObject;
        }
    } catch (XmlException e) {
        log.error("Error parsing response.", e);

        // TODO add handling to identify HTML response
        // if (responseString.contains(HTML_TAG_IN_RESPONSE)) {
        // log.error("Received HTML!\n" + responseString + "\n");
        // }

        String msg = "Could not parse response (received via " + requestMethod + ") to the request\n\n"
                + request + "\n\n\n" + Tools.getStackTrace(e);
        // msg = msg + "\n\nRESPONSE STRING:\n<![CDATA[" + responseObject.xmlText() + "]]>";

        OwsExceptionReport er = new OwsExceptionReport(ExceptionCode.NoApplicableCode, "Client.doSend()", msg);
        return er.getDocument();
    } catch (Exception e) {
        log.error("Error executing method on httpClient.", e);
        return new OwsExceptionReport(ExceptionCode.NoApplicableCode, "service", e.getMessage()).getDocument();
    }
}

From source file:com.groupon.odo.client.Client.java

protected static String doGet(String fullUrl, int timeout) throws Exception {
    HttpGet get = new HttpGet(fullUrl);

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), timeout);
    HttpConnectionParams.setSoTimeout(client.getParams(), timeout);

    HttpResponse response = client.execute(get);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String accumulator = "";
    String line = "";
    while ((line = rd.readLine()) != null) {
        accumulator += line;//from   ww w .j av a2  s .  com
        accumulator += "\n";
    }
    return accumulator;
}

From source file:com.basho.riak.client.http.util.TestClientUtils.java

@Test
public void newHttpClient_sets_connection_timeout() {
    final int timeout = 11;
    config.setTimeout(timeout);/*from   ww  w .  ja v a  2 s  . c  om*/

    HttpClient httpClient = ClientUtils.newHttpClient(config);

    assertEquals(timeout, httpClient.getParams().getIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 1));
    assertEquals(timeout, httpClient.getParams().getIntParameter(AllClientPNames.SO_TIMEOUT, 1));
}

From source file:org.andstatus.app.net.HttpConnectionBasic.java

/**
 * Execute a GET request against the Twitter REST API.
 * //from   ww w . ja  va2 s. com
 * @param url
 * @return String
 * @throws ConnectionException
 */
@Override
public JSONTokener getRequest(HttpGet getMethod) throws ConnectionException {
    JSONTokener jso = null;
    String response = null;
    boolean ok = false;
    int statusCode = 0;
    HttpClient client = HttpApacheUtils.getHttpClient();
    try {
        getMethod.setHeader("User-Agent", HttpConnection.USER_AGENT);
        getMethod.addHeader("Authorization", "Basic " + getCredentials());
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                MyPreferences.getConnectionTimeoutMs());
        client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                MyPreferences.getConnectionTimeoutMs());
        HttpResponse httpResponse = client.execute(getMethod);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        response = retrieveInputStream(httpResponse.getEntity());
        jso = new JSONTokener(response);
        ok = true;
    } catch (Exception e) {
        MyLog.e(this, "getRequest", e);
        throw new ConnectionException(e);
    } finally {
        getMethod.abort();
    }
    parseStatusCode(statusCode);
    if (!ok) {
        jso = null;
    }
    return jso;
}

From source file:org.eclipse.skalli.services.extension.validators.HostReachableValidator.java

protected void validate(SortedSet<Issue> issues, UUID entityId, Object value, final Severity minSeverity,
        int item) {
    if (value == null) {
        return;/*ww  w.ja v a2  s.co m*/
    }

    URL url = null;
    String label = null;
    if (value instanceof URL) {
        url = (URL) value;
        label = url.toExternalForm();
    } else if (value instanceof Link) {
        Link link = (Link) value;
        try {
            url = URLUtils.stringToURL(link.getUrl());
            label = link.getLabel();
        } catch (MalformedURLException e) {
            CollectionUtils.addSafe(issues,
                    getIssueByReachableHost(minSeverity, entityId, item, link.getUrl()));
        }
    } else {
        try {
            url = URLUtils.stringToURL(value.toString());
            label = url != null ? url.toExternalForm() : value.toString();
        } catch (MalformedURLException e) {
            CollectionUtils.addSafe(issues,
                    getIssueByReachableHost(minSeverity, entityId, item, value.toString()));
        }
    }

    if (url == null) {
        return;
    }

    HttpClient client = Destinations.getClient(url);
    if (client != null) {
        HttpResponse response = null;
        try {
            HttpParams params = client.getParams();
            HttpClientParams.setRedirecting(params, false); // we want to find 301 MOVED PERMANTENTLY
            HttpGet method = new HttpGet(url.toExternalForm());
            LOG.info("GET " + url); //$NON-NLS-1$
            response = client.execute(method);
            int status = response.getStatusLine().getStatusCode();
            LOG.info(status + " " + response.getStatusLine().getReasonPhrase()); //$NON-NLS-1$
            CollectionUtils.addSafe(issues,
                    getIssueByResponseCode(minSeverity, entityId, item, response.getStatusLine(), label));
        } catch (UnknownHostException e) {
            issues.add(newIssue(Severity.ERROR, entityId, item, TXT_HOST_UNKNOWN, url.getHost()));
        } catch (ConnectException e) {
            issues.add(newIssue(Severity.ERROR, entityId, item, TXT_CONNECT_FAILED, url.getHost()));
        } catch (MalformedURLException e) {
            issues.add(newIssue(Severity.ERROR, entityId, item, TXT_MALFORMED_URL, url));
        } catch (IOException e) {
            LOG.warn(MessageFormat.format("I/O Exception on validation: {0}", e.getMessage()), e); //$NON-NLS-1$
        } catch (RuntimeException e) {
            LOG.error(MessageFormat.format("RuntimeException on validation: {0}", e.getMessage()), e); //$NON-NLS-1$
        } finally {
            HttpUtils.consumeQuietly(response);
        }
    } else {
        CollectionUtils.addSafe(issues, getIssueByReachableHost(minSeverity, entityId, item, url.getHost()));
    }
}

From source file:org.switchyard.component.http.OutboundHandler.java

/**
 * The handler method that invokes the actual HTTP service when the
 * component is used as a HTTP consumer.
 * @param exchange the Exchange//w w w  . ja  v a 2s  .c  o m
 * @throws HandlerException handler exception
 */
@Override
public void handleMessage(final Exchange exchange) throws HandlerException {
    // identify ourselves
    exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE)
            .addLabels(BehaviorLabel.TRANSIENT.label());
    if (getState() != State.STARTED) {
        final String m = HttpMessages.MESSAGES.bindingNotStarted(_referenceName, _bindingName);
        LOGGER.error(m);
        throw new HandlerException(m);
    }

    HttpClient httpclient = new DefaultHttpClient();
    if (_timeout != null) {
        HttpParams httpParams = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, _timeout);
        HttpConnectionParams.setSoTimeout(httpParams, _timeout);
    }
    try {
        if (_credentials != null) {
            ((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(_authScope, _credentials);
            List<String> authpref = new ArrayList<String>();
            authpref.add(AuthPolicy.NTLM);
            authpref.add(AuthPolicy.BASIC);
            httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
        }
        if (_proxyHost != null) {
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxyHost);
        }
        HttpBindingData httpRequest = _messageComposer.decompose(exchange, new HttpRequestBindingData());
        HttpRequestBase request = null;
        if (_httpMethod.equals(HTTP_GET)) {
            request = new HttpGet(_baseAddress);
        } else if (_httpMethod.equals(HTTP_POST)) {
            request = new HttpPost(_baseAddress);
            ((HttpPost) request).setEntity(new BufferedHttpEntity(
                    new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())));
        } else if (_httpMethod.equals(HTTP_DELETE)) {
            request = new HttpDelete(_baseAddress);
        } else if (_httpMethod.equals(HTTP_HEAD)) {
            request = new HttpHead(_baseAddress);
        } else if (_httpMethod.equals(HTTP_PUT)) {
            request = new HttpPut(_baseAddress);
            ((HttpPut) request).setEntity(new BufferedHttpEntity(
                    new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())));
        } else if (_httpMethod.equals(HTTP_OPTIONS)) {
            request = new HttpOptions(_baseAddress);
        }
        Iterator<Map.Entry<String, List<String>>> entries = httpRequest.getHeaders().entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, List<String>> entry = entries.next();
            String name = entry.getKey();
            if (REQUEST_HEADER_BLACKLIST.contains(name)) {
                HttpLogger.ROOT_LOGGER.removingProhibitedRequestHeader(name);
                continue;
            }
            List<String> values = entry.getValue();
            for (String value : values) {
                request.addHeader(name, value);
            }
        }
        if (_contentType != null) {
            request.addHeader("Content-Type", _contentType);
        }

        HttpResponse response = null;
        if ((_credentials != null) && (_credentials instanceof NTCredentials)) {
            // Send a request for the Negotiation
            response = httpclient.execute(new HttpGet(_baseAddress));
            HttpClientUtils.closeQuietly(response);
        }
        if (_authCache != null) {
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, _authCache);
            response = httpclient.execute(request, context);
        } else {
            response = httpclient.execute(request);
        }
        int status = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        HttpResponseBindingData httpResponse = new HttpResponseBindingData();
        Header[] headers = response.getAllHeaders();
        for (Header header : headers) {
            httpResponse.addHeader(header.getName(), header.getValue());
        }
        if (entity != null) {
            if (entity.getContentType() != null) {
                httpResponse.setContentType(new ContentType(entity.getContentType().getValue()));
            } else {
                httpResponse.setContentType(new ContentType());
            }
            httpResponse.setBodyFromStream(entity.getContent());
        }
        httpResponse.setStatus(status);
        Message out = _messageComposer.compose(httpResponse, exchange);
        if (httpResponse.getStatus() < 400) {
            exchange.send(out);
        } else {
            exchange.sendFault(out);
        }
    } catch (Exception e) {
        final String m = HttpMessages.MESSAGES.unexpectedExceptionHandlingHTTPMessage();
        LOGGER.error(m, e);
        throw new HandlerException(m, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.dongfang.dicos.sina.UtilSina.java

/**
 * Get a HttpClient object which is setting correctly .
 * /*from   www. ja v a2s . c  o m*/
 * @param context
 *            : context of activity
 * @return HttpClient: HttpClient object
 */
public static HttpClient getHttpClient(Context context) {
    BasicHttpParams httpParameters = new BasicHttpParams();
    // Set the default socket timeout (SO_TIMEOUT) // in
    // milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, UtilSina.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, UtilSina.SET_SOCKET_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParameters);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        // ??APN
        Uri uri = Uri.parse("content://telephony/carriers/preferapn");
        Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            // ???
            String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
            if (proxyStr != null && proxyStr.trim().length() > 0) {
                HttpHost proxy = new HttpHost(proxyStr, 80);
                client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
            }
            mCursor.close();
        }
    }
    return client;
}