Example usage for org.apache.http.params HttpParams setParameter

List of usage examples for org.apache.http.params HttpParams setParameter

Introduction

In this page you can find the example usage for org.apache.http.params HttpParams setParameter.

Prototype

HttpParams setParameter(String str, Object obj);

Source Link

Usage

From source file:com.ibuildapp.romanblack.TableReservationPlugin.utils.TableReservationHTTP.java

/**
 * This method sends HTTP request to get list of reservations.
 *
 * @param user      user// ww  w. j  a  v  a  2s  .c  om
 * @param orderInfo order info
 * @return result
 */
public static String sendListOrdersRequest(User user, TableReservationInfo orderInfo) {
    HttpParams httpParameters = new BasicHttpParams();
    httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 5000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = null;
    List<NameValuePair> nameValuePairs = null;

    httppost = new HttpPost(LIST_ORDER_URL);
    Log.e(TAG, "LIST_ORDER_URL = " + LIST_ORDER_URL);

    nameValuePairs = new ArrayList<NameValuePair>();

    // user details
    nameValuePairs.add(new BasicNameValuePair("app_id", orderInfo.getAppid()));
    nameValuePairs.add(new BasicNameValuePair("module_id", orderInfo.getModuleid()));
    nameValuePairs.add(new BasicNameValuePair("user_id", user.getAccountId()));

    // add security part
    nameValuePairs.add(new BasicNameValuePair("app_id", Statics.appId));
    nameValuePairs.add(new BasicNameValuePair("token", Statics.appToken));

    // user details
    String userType = null;
    if (user.getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) {
        userType = "facebook";
    } else if (user.getAccountType() == User.ACCOUNT_TYPES.TWITTER) {
        userType = "twitter";
    } else if (user.getAccountType() == User.ACCOUNT_TYPES.IBUILDAPP) {
        userType = "ibuildapp";
    } else if (user.getAccountType() == User.ACCOUNT_TYPES.GUEST) {
        userType = "guest";
    }
    nameValuePairs.add(new BasicNameValuePair("user_type", userType));

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException uEEx) {
        Log.e("", "");
        return "error";
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        String strResponseSaveGoal;
        strResponseSaveGoal = httpclient.execute(httppost, responseHandler);
        String error = JSONParser.parseQueryError(strResponseSaveGoal);

        if (error == null || error.length() == 0) {
            return strResponseSaveGoal;
        } else {
            return "error";
        }

    } catch (ConnectTimeoutException conEx) {
        Log.d("sendListOrdersRequest", "");
        return "error";
    } catch (ClientProtocolException ex) {
        Log.d("sendListOrdersRequest", "");
        return "error";
    } catch (IOException ex) {
        Log.d("sendListOrdersRequest", "");
        return "error";
    }
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

public static Element sendGet(ConnectorManager connectorManager, String servletPath,
        Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }/*from   ww w. j a v a2s.co  m*/

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            String target = connectorManager.getUrl() + servletPath;
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);

                if (firstParam) {
                    target += "?";
                    firstParam = false;
                } else {
                    target += "&";
                }
                target += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", target);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (Exception e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnector.java

private static HttpParams createHttpParams(final RemoteStorageContext ctx) {
    final HttpParams params = new BasicHttpParams();

    // getting the timeout from RemoteStorageContext. The value we get depends on per-repo and global settings.
    // The value will "cascade" from repo level to global level, see implementation.
    int timeout = ctx.getRemoteConnectionSettings().getConnectionTimeout();

    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    return params;
}

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

public static Element sendGet(String openSearchServerURLStr, Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }//  w  ww.  j  av  a2  s  .co m

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, CharSetUtils.UTF_8);
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL openSearchServerURL = new URL(openSearchServerURLStr);
        String host = openSearchServerURL.getHost();
        int port = openSearchServerURL.getPort();
        if (port == -1) {
            port = 80;
        }
        HttpHost httpHost = new HttpHost(host, port);

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);

        try {
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);
                if (paramValue != null) {
                    try {
                        paramValue = URLEncoder.encode(paramValue, CharSetUtils.ISO_8859_1);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (firstParam) {
                    openSearchServerURLStr += "?";
                    firstParam = false;
                } else {
                    openSearchServerURLStr += "&";
                }
                openSearchServerURLStr += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host, port);
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET",
                    openSearchServerURLStr);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (RuntimeException e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.sisob.uma.api.crawler4j.crawler.PageFetcher.java

public synchronized static void startConnectionMonitorThread() {
    if (connectionMonitorThread == null) {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
        paramsBean.setVersion(HttpVersion.HTTP_1_1);
        paramsBean.setContentCharset("UTF-8");
        paramsBean.setUseExpectContinue(false);

        params.setParameter("http.useragent", Configurations.getStringProperty("fetcher.user_agent",
                "crawler4j (http://code.google.com/p/crawler4j/)"));

        params.setIntParameter("http.socket.timeout",
                Configurations.getIntProperty("fetcher.socket_timeout", 20000));

        params.setIntParameter("http.connection.timeout",
                Configurations.getIntProperty("fetcher.connection_timeout", 30000));

        params.setBooleanParameter("http.protocol.handle-redirects", false);

        ConnPerRouteBean connPerRouteBean = new ConnPerRouteBean();
        connPerRouteBean// www  .  j  av  a  2s  .co m
                .setDefaultMaxPerRoute(Configurations.getIntProperty("fetcher.max_connections_per_host", 100));
        ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRouteBean);
        ConnManagerParams.setMaxTotalConnections(params,
                Configurations.getIntProperty("fetcher.max_total_connections", 100));

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        if (Configurations.getBooleanProperty("fetcher.crawl_https", false)) {
            schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        }

        connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

        ProjectLogger.LOGGER.setLevel(Level.INFO);
        httpclient = new DefaultHttpClient(connectionManager, params);
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:com.vk.sdkweb.api.httpClient.VKHttpClient.java

/**
 * Creates the http client (if need). Returns reusing client
 *
 * @return Prepared client used for API requests loading
 *///www .  j a v a2s.co m
public static VKHttpClient getClient() {
    if (sInstance == null) {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        HttpParams params = new BasicHttpParams();
        Context ctx = VKUIHelper.getTopActivity();

        try {
            if (ctx != null) {
                PackageManager packageManager = ctx.getPackageManager();
                if (packageManager != null) {
                    PackageInfo info = packageManager.getPackageInfo(ctx.getPackageName(), 0);
                    params.setParameter(CoreProtocolPNames.USER_AGENT,
                            String.format(Locale.US, "%s/%s (%s; Android %d; Scale/%.2f; VK SDK %s; %s)",
                                    VKUtil.getApplicationName(ctx), info.versionName, Build.MODEL,
                                    Build.VERSION.SDK_INT, ctx.getResources().getDisplayMetrics().density,
                                    VKSdkVersion.SDK_VERSION, info.packageName));
                }
            }
        } catch (Exception ignored) {
        }
        sInstance = new VKHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
    }
    return sInstance;
}

From source file:com.amalto.workbench.utils.HttpClientUtil.java

private static DefaultHttpClient createClient() {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIMEOUT);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
    params.setParameter(CoreConnectionPNames.TCP_NODELAY, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    return new DefaultHttpClient(cm, params);
}

From source file:com.vk.sdk.api.httpClient.VKHttpClient.java

/**
 * Creates the http client (if need). Returns reusing client
 *
 * @return Prepared client used for API requests loading
 *//*  w  ww .j av  a2 s  .c  om*/
public static VKHttpClient getClient() {
    if (sInstance == null) {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        HttpParams params = new BasicHttpParams();
        Context ctx = VKUIHelper.getApplicationContext();

        try {
            if (ctx != null) {
                PackageManager packageManager = ctx.getPackageManager();
                if (packageManager != null) {
                    PackageInfo info = packageManager.getPackageInfo(ctx.getPackageName(), 0);
                    params.setParameter(CoreProtocolPNames.USER_AGENT,
                            String.format(Locale.US, "%s/%s (%s; Android %d; Scale/%.2f; VK SDK %s; %s)",
                                    VKUtil.getApplicationName(ctx), info.versionName, Build.MODEL,
                                    Build.VERSION.SDK_INT, ctx.getResources().getDisplayMetrics().density,
                                    VKSdkVersion.SDK_VERSION, info.packageName));
                }
            }
        } catch (Exception ignored) {
        }
        sInstance = new VKHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
    }
    return sInstance;
}

From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java

private static ApptentiveHttpResponse performHttpRequest(String oauthToken, String uri, Method method,
        String body) {// w  w w .j a v a  2  s .  c o m
    Log.d("Performing request to %s", uri);
    //Log.e("OAUTH Token: %s", oauthToken);

    ApptentiveHttpResponse ret = new ApptentiveHttpResponse();
    HttpClient httpClient = null;
    try {
        HttpRequestBase request;
        httpClient = new DefaultHttpClient();
        switch (method) {
        case GET:
            request = new HttpGet(uri);
            break;
        case PUT:
            request = new HttpPut(uri);
            request.setHeader("Content-Type", "application/json");
            Log.d("PUT body: " + body);
            ((HttpPut) request).setEntity(new StringEntity(body, "UTF-8"));
            break;
        case POST:
            request = new HttpPost(uri);
            request.setHeader("Content-Type", "application/json");
            Log.d("POST body: " + body);
            ((HttpPost) request).setEntity(new StringEntity(body, "UTF-8"));
            break;
        default:
            Log.e("Unrecognized method: " + method.name());
            return ret;
        }

        HttpParams httpParams = request.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_HTTP_CONNECT_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_HTTP_SOCKET_TIMEOUT);
        httpParams.setParameter("http.useragent", getUserAgentString());
        request.setHeader("Authorization", "OAuth " + oauthToken);
        request.setHeader("Accept-Encoding", "gzip");
        request.setHeader("Accept", "application/json");
        request.setHeader("X-API-Version", API_VERSION);

        HttpResponse response = httpClient.execute(request);
        int code = response.getStatusLine().getStatusCode();
        ret.setCode(code);
        ret.setReason(response.getStatusLine().getReasonPhrase());
        Log.d("Response Status Line: " + response.getStatusLine().toString());

        HeaderIterator headerIterator = response.headerIterator();
        if (headerIterator != null) {
            Map<String, String> headers = new HashMap<String, String>();
            while (headerIterator.hasNext()) {
                Header header = (Header) headerIterator.next();
                headers.put(header.getName(), header.getValue());
                //Log.v("Header: %s = %s", header.getName(), header.getValue());
            }
            ret.setHeaders(headers);
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            if (is != null) {
                String contentEncoding = ret.getHeaders().get("Content-Encoding");
                if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
                    is = new GZIPInputStream(is);
                }
                ret.setContent(Util.readStringFromInputStream(is, "UTF-8"));
                if (code >= 200 && code < 300) {
                    Log.d("Response: " + ret.getContent());
                } else {
                    Log.w("Response: " + ret.getContent());
                }
            }
        }
    } catch (IllegalArgumentException e) {
        Log.w("Error communicating with server.", e);
    } catch (SocketTimeoutException e) {
        Log.w("Timeout communicating with server.");
    } catch (IOException e) {
        Log.w("Error communicating with server.", e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return ret;
}

From source file:org.igniterealtime.jbosh.ApacheHTTPSender.java

@SuppressWarnings("deprecation")
private static synchronized HttpClient initHttpClient(final BOSHClientConfig config) {
    // Create and initialize HTTP parameters
    org.apache.http.params.HttpParams params = new org.apache.http.params.BasicHttpParams();
    org.apache.http.conn.params.ConnManagerParams.setMaxTotalConnections(params, 100);
    org.apache.http.params.HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    org.apache.http.params.HttpProtocolParams.setUseExpectContinue(params, false);
    if (config != null && config.getProxyHost() != null && config.getProxyPort() != 0) {
        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        params.setParameter(org.apache.http.conn.params.ConnRoutePNames.DEFAULT_PROXY, proxy);
    }/*from  w  w w . j  a  v  a2 s . com*/

    // Create and initialize scheme registry 
    org.apache.http.conn.scheme.SchemeRegistry schemeRegistry = new org.apache.http.conn.scheme.SchemeRegistry();
    schemeRegistry.register(new org.apache.http.conn.scheme.Scheme("http",
            org.apache.http.conn.scheme.PlainSocketFactory.getSocketFactory(), 80));
    org.apache.http.conn.ssl.SSLSocketFactory sslFactory = org.apache.http.conn.ssl.SSLSocketFactory
            .getSocketFactory();
    sslFactory.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new org.apache.http.conn.scheme.Scheme("https", sslFactory, 443));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    org.apache.http.conn.ClientConnectionManager cm = new org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager(
            params, schemeRegistry);
    return new org.apache.http.impl.client.DefaultHttpClient(cm, params);
}