Example usage for org.apache.http.params BasicHttpParams BasicHttpParams

List of usage examples for org.apache.http.params BasicHttpParams BasicHttpParams

Introduction

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

Prototype

public BasicHttpParams() 

Source Link

Usage

From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java

public WebbasedProcessor() {
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(CookieSpecPNames.DATE_PATTERNS,
            Arrays.asList("EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd MMM yyyy HH:mm:ss z"));
    httpClient = new DefaultHttpClient(params);
    cookieStore = new BasicCookieStore();
    context = new BasicHttpContext();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:org.openiot.gsn.http.rest.RestRemoteWrapper.java

private HttpParams getHttpClientParams(int timeout) {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpConnectionParams.setTcpNoDelay(params, false);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); // Set the connection time to 30s
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpProtocolParams.setUserAgent(params, "GSN-HTTP-CLIENT");
    return params;
}

From source file:jsonbroker.library.client.http.HttpDispatcher.java

public HttpDispatcher(NetworkAddress networkAddress) {

    _networkAddress = networkAddress;// w  ww  .j av  a  2  s.  co  m

    /*
      with ... 
      _client = new DefaultHttpClient();
      ... we get the following error ... 
      "Invalid use of SingleClientConnManager: connection still allocated.\nMake sure to release the connection before allocating another one."
      ... using a thread safe connecion manager ... 
      * http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html
      * http://thinkandroid.wordpress.com/2009/12/31/creating-an-http-client-example/ 
     */

    //sets up parameters
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    // timeouts ... 
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);

    //registers schemes for both http and https
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    registry.register(new Scheme("https", sslSocketFactory, 443));

    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
    _client = new DefaultHttpClient(manager, params);

}

From source file:com.attentec.ServerContact.java

/**
 * Posts POST request to url with data that from values.
 * Values are put together to a json object before they are sent to server.
 * postname = { subvar_1_name => subvar_1_value,
 *             subvar_2_name => subvar_2_value
 *             ...}/*from  w w  w .j  av  a  2s  .com*/
 * postname_2 = {...}
 * ...
 * @param values hashtable with structure:
 * @param url path on the server to call
 * @param ctx calling context
 * @return JSONObject with data from rails server.
 * @throws Login.LoginException when login is wrong
 */
public static JSONObject postJSON(final Hashtable<String, List<NameValuePair>> values, final String url,
        final Context ctx) throws Login.LoginException {
    //fetch the urlbase
    urlbase = PreferencesHelper.getServerUrlbase(ctx);

    //create a JSONObject of the hashtable
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    Enumeration<String> postnames = values.keys();

    String postname;
    List<NameValuePair> postvalues;
    JSONObject postdata;

    while (postnames.hasMoreElements()) {
        postname = (String) postnames.nextElement();
        postvalues = values.get(postname);
        postdata = new JSONObject();
        for (int i = 0; i < postvalues.size(); i++) {
            try {
                postdata.put(postvalues.get(i).getName(), postvalues.get(i).getValue());
            } catch (JSONException e) {
                Log.w(TAG, "JSON fail");
                return null;
            }
        }
        pairs.add(new BasicNameValuePair(postname, postdata.toString()));
    }

    //prepare the http call
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);

    HttpClient client = new DefaultHttpClient(httpParams);

    HttpPost post = new HttpPost(urlbase + url);
    //Log.d(TAG, "contacting url: " + post.getURI());
    try {
        post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return null;
    }

    //call the server
    String response = null;
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        response = client.execute(post, responseHandler);
    } catch (IOException e) {
        Log.e(TAG, "Failed in HTTP request: " + e.toString());
        return null;
    }
    //Log.d(TAG, "Have contacted url success: " + post.getURI());
    //read response
    JSONObject jsonresponse;
    try {

        jsonresponse = new JSONObject(response);
    } catch (JSONException e) {
        Log.e(TAG, "Incorrect response from server" + e.toString());
        return null;
    }
    String responsestatus;
    try {
        responsestatus = jsonresponse.getString("Responsestatus");
    } catch (JSONException e1) {
        return null;
    }
    if (!responsestatus.equals("Wrong login")) {
        return jsonresponse;
    } else {
        Log.w(TAG, "Wrong login");
        throw new Login.LoginException("Wrong login");
    }
}

From source file:com.woonoz.proxy.servlet.ProxyServlet.java

public void init(ProxyServletConfig config) {
    targetServer = config.getTargetUrl();
    if (targetServer != null) {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme(targetServer.getProtocol(), getPortOrDefault(targetServer.getPort()),
                PlainSocketFactory.getSocketFactory()));
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, config.getConnectionTimeout());
        HttpConnectionParams.setSoTimeout(httpParams, config.getSocketTimeout());
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
        cm.setDefaultMaxPerRoute(config.getMaxConnections());
        cm.setMaxTotal(config.getMaxConnections());
        client = new DefaultHttpClient(cm, httpParams);
        client.removeResponseInterceptorByClass(ResponseProcessCookies.class);
        client.removeRequestInterceptorByClass(RequestAddCookies.class);

        final String remoteUserHeader = config.getRemoteUserHeader();
        if (null != remoteUserHeader) {
            client.addRequestInterceptor(new HttpRequestInterceptor() {

                @Override//from  w ww .jav  a 2s . com
                public void process(HttpRequest request, HttpContext context)
                        throws HttpException, IOException {
                    request.removeHeaders(remoteUserHeader);
                    HttpRequestHandler handler;
                    if (context != null && (handler = (HttpRequestHandler) context
                            .getAttribute(HttpRequestHandler.class.getName())) != null) {
                        String remoteUser = handler.getRequest().getRemoteUser();
                        if (remoteUser != null) {
                            request.addHeader(remoteUserHeader, remoteUser);
                        }
                    }
                }
            });
        }
    }
}

From source file:com.proofpoint.http.client.ApacheHttpClient.java

public ApacheHttpClient(HttpClientConfig config, Set<? extends HttpRequestFilter> requestFilters) {
    Preconditions.checkNotNull(config, "config is null");
    Preconditions.checkNotNull(requestFilters, "requestFilters is null");

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(config.getMaxConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerServer());

    BasicHttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT,
            Ints.checkedCast(config.getReadTimeout().toMillis()));
    httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            Ints.checkedCast(config.getConnectTimeout().toMillis()));
    httpParams.setParameter(CoreConnectionPNames.SO_LINGER, 0); // do we need this?

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, httpParams);
    defaultHttpClient.setKeepAliveStrategy(new FixedIntervalKeepAliveStrategy(config.getKeepAliveInterval()));
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    this.httpClient = defaultHttpClient;

    this.requestFilters = ImmutableList.copyOf(requestFilters);
}

From source file:com.imaginary.home.controller.CloudService.java

static private @Nonnull HttpClient getClient(@Nonnull String endpoint, @Nullable String proxyHost,
        int proxyPort) {
    boolean ssl = endpoint.startsWith("https");
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "Imaginary Home");

    if (proxyHost != null) {
        if (proxyPort < 0) {
            proxyPort = 0;/*  w w  w . ja  v  a 2s .co  m*/
        }
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http"));
    }
    return new DefaultHttpClient(params);
}

From source file:org.cgiar.ilri.odk.pull.backend.DataHandler.java

/**
 * Performs a HTTP/HTTPS request to the server
 *
 * @param context       Context e.g activity that is making request
 * @param jsonString    The {@link org.json.JSONObject} or {@link org.json.JSONArray} string to
 *                      be sent to the server
 * @param appendedURL   The URI to be appended to the BASE_URL
 *
 * @return  String containing the response from the server or null if an error occurs
 *//*from   w  w  w .jav  a 2s .  c  o  m*/
public static String sendDataToServer(Context context, String jsonString, String appendedURL) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, HTTP_POST_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, HTTP_RESPONSE_TIMEOUT);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpGet httpGet = new HttpGet(BASE_URL + appendedURL);
    try {
        //List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
        //nameValuePairs.add(new BasicNameValuePair("json", jsonString));
        //httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                String responseString = convertStreamToString(inputStream);
                return responseString.trim();
            }
        } else {
            Log.e(TAG,
                    "Status Code " + String.valueOf(httpResponse.getStatusLine().getStatusCode()) + " passed");
        }
    } catch (Exception e) {
        e.printStackTrace();
        setSharedPreference(context, "http_error", e.getMessage());
    }
    if (isConnectedToServer(HTTP_POST_TIMEOUT)) {
        setSharedPreference(context, "http_error",
                "This application was unable to reach http://azizi.ilri.cgiar.org within "
                        + String.valueOf(HTTP_POST_TIMEOUT / 1000)
                        + " seconds. Try resetting your network connection");
    }
    return null;
}

From source file:org.siddhiesb.transport.passthru.config.BaseConfiguration.java

protected HttpParams buildHttpParams() {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SO_TIMEOUT,
            conf.getIntProperty(HttpConnectionParams.SO_TIMEOUT, 60000))
            .setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                    conf.getIntProperty(HttpConnectionParams.CONNECTION_TIMEOUT, 0))
            .setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE,
                    conf.getIntProperty(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024))
            .setParameter(HttpProtocolParams.ORIGIN_SERVER,
                    conf.getStringProperty(HttpProtocolParams.ORIGIN_SERVER, "WSO2-PassThrough-HTTP"))
            .setParameter(HttpProtocolParams.USER_AGENT,
                    conf.getStringProperty(HttpProtocolParams.USER_AGENT, "Synapse-PT-HttpComponents-NIO"));

    return params;
}

From source file:com.hoccer.http.AsyncHttpRequest.java

public AsyncHttpRequest(String pUrl) {
    mRequest = createRequest(pUrl);// w  ww  .j ava 2 s  . c om

    HttpParams httpParams = new BasicHttpParams();
    setHttpClient(new HttpClientWithKeystore(httpParams));
}