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

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

Introduction

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

Prototype

HttpParams setBooleanParameter(String str, boolean z);

Source Link

Usage

From source file:com.google.apphosting.vmruntime.VmApiProxyDelegate.java

/**
 * Create an HTTP post request suitable for sending to the API server.
 *
 * @param environment The current VMApiProxyEnvironment
 * @param packageName The API call package
 * @param methodName The API call method
 * @param requestData The POST payload./*from w w  w.  j a  v  a 2s  .  co  m*/
 * @param timeoutMs The timeout for this request
 * @return an HttpPost object to send to the API.
 */
// 
static HttpPost createRequest(VmApiProxyEnvironment environment, String packageName, String methodName,
        byte[] requestData, int timeoutMs) {
    // Wrap the payload in a RemoteApi Request.
    RemoteApiPb.Request remoteRequest = new RemoteApiPb.Request();
    remoteRequest.setServiceName(packageName);
    remoteRequest.setMethod(methodName);
    remoteRequest.setRequestId(environment.getTicket());
    remoteRequest.setRequestAsBytes(requestData);

    HttpPost request = new HttpPost("http://" + environment.getServer() + REQUEST_ENDPOINT);
    request.setHeader(RPC_STUB_ID_HEADER, REQUEST_STUB_ID);
    request.setHeader(RPC_METHOD_HEADER, REQUEST_STUB_METHOD);

    // Set TCP connection timeouts.
    HttpParams params = new BasicHttpParams();
    params.setLongParameter(ConnManagerPNames.TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);

    // Performance tweaks.
    params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.TRUE);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, Boolean.FALSE);
    request.setParams(params);

    // The request deadline can be overwritten by the environment, read deadline if available.
    Double deadline = (Double) (environment.getAttributes().get(API_DEADLINE_KEY));
    if (deadline == null) {
        request.setHeader(RPC_DEADLINE_HEADER,
                Double.toString(TimeUnit.SECONDS.convert(timeoutMs, TimeUnit.MILLISECONDS)));
    } else {
        request.setHeader(RPC_DEADLINE_HEADER, Double.toString(deadline));
    }

    // If the incoming request has a dapper trace header: set it on outgoing API calls
    // so they are tied to the original request.
    Object dapperHeader = environment.getAttributes()
            .get(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey);
    if (dapperHeader instanceof String) {
        request.setHeader(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey, (String) dapperHeader);
    }

    // If the incoming request has a Cloud trace header: set it on outgoing API calls
    // so they are tied to the original request.
    // TODO(user): For now, this uses the incoming span id - use the one from the active span.
    Object traceHeader = environment.getAttributes()
            .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey);
    if (traceHeader instanceof String) {
        request.setHeader(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.headerKey,
                (String) traceHeader);
    }

    ByteArrayEntity postPayload = new ByteArrayEntity(remoteRequest.toByteArray(),
            ContentType.APPLICATION_OCTET_STREAM);
    postPayload.setChunked(false);
    request.setEntity(postPayload);

    return request;
}

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/*from  ww  w.  jav a  2  s  .  c  o 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.jgoetsch.eventtrader.source.WordPressLoginFilter.java

public void doAction(HttpClient client, AbstractHttpMsgSource httpMsgSource) {
    try {/*w ww .j  a v  a2  s .c  om*/
        if (getLoginUrl() == null || getLoginUrl().length() == 0)
            throw new IllegalStateException("Required property \"loginUrl\" not set");
        else {
            HttpPost post = new HttpPost(getLoginUrl());
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("log", httpMsgSource.getUsername()));
            nvps.add(new BasicNameValuePair("pwd", httpMsgSource.getPassword()));
            nvps.add(new BasicNameValuePair("redirect_to", "wp-admin/"));
            nvps.add(new BasicNameValuePair("testcookie", "1"));
            post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            HttpParams postParams = new BasicHttpParams();
            postParams.setBooleanParameter("http.protocol.handle-redirects", false);
            post.setParams(postParams);

            HttpResponse rsp = client.execute(post);
            HttpEntity entity = rsp.getEntity();
            if (entity != null)
                entity.consumeContent(); // release connection gracefully

            if (rsp.getStatusLine().getStatusCode() >= 400)
                throw new IOException("Login POST request failed with error code " + rsp.getStatusLine());
            else if (rsp.getStatusLine().getStatusCode() != 302)
                throw new IOException(
                        "Login failed, redirect response not received (probably incorrect username/password)");
            else {
                log.debug("Successfully logged into " + getLoginUrl() + " as user "
                        + httpMsgSource.getUsername());
            }
        }
    } catch (IOException e) {
        log.error("Wordpress site login failed", e);
    }

}

From source file:com.quantcast.measurement.service.QCDataUploader.java

String synchronousUploadEvents(Collection<QCEvent> events) {
    if (events == null || events.isEmpty())
        return null;

    String uploadId = QCUtility.generateUniqueId();

    JSONObject upload = new JSONObject();
    try {/*from ww  w.j  a v a 2s . c om*/
        upload.put(QC_UPLOAD_ID_KEY, uploadId);
        upload.put(QC_QCV_KEY, QCUtility.API_VERSION);
        upload.put(QCEvent.QC_APIKEY_KEY, QCMeasurement.INSTANCE.getApiKey());
        upload.put(QCEvent.QC_NETWORKCODE_KEY, QCMeasurement.INSTANCE.getNetworkCode());
        upload.put(QCEvent.QC_DEVICEID_KEY, QCMeasurement.INSTANCE.getDeviceId());

        JSONArray event = new JSONArray();
        for (QCEvent e : events) {
            event.put(new JSONObject(e.getParameters()));
        }
        upload.put(QC_EVENTS_KEY, event);
    } catch (JSONException e) {
        QCLog.e(TAG, "Error while encoding json.");
        return null;
    }

    int code;
    String url = QCUtility.addScheme(UPLOAD_URL_WITHOUT_SCHEME);
    final DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    defaultHttpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
    final BasicHttpContext localContext = new BasicHttpContext();

    try {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        StringEntity se = new StringEntity(upload.toString(), HTTP.UTF_8);
        post.setEntity(se);

        HttpParams params = new BasicHttpParams();
        params.setBooleanParameter("http.protocol.expect-continue", false);
        post.setParams(params);

        HttpResponse response = defaultHttpClient.execute(post, localContext);
        code = response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        QCLog.e(TAG, "Could not upload events", e);
        QCMeasurement.INSTANCE.logSDKError("json-upload-failure", e.toString(), null);
        code = HttpStatus.SC_REQUEST_TIMEOUT;
    }

    if (!isSuccessful(code)) {
        uploadId = null;
        QCLog.e(TAG, "Events not sent to server. Response code: " + code);
        QCMeasurement.INSTANCE.logSDKError("json-upload-failure",
                "Bad response from server. Response code: " + code, null);
    }
    return uploadId;
}

From source file:org.sonatype.nexus.test.utils.hc4client.Hc4ClientHelper.java

@Override
public void start() throws Exception {
    super.start();

    HttpParams params = new SyncBasicHttpParams();
    params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, getConnectTimeout());
    params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, getReadTimeout());
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    final PoolingClientConnectionManager connManager = new PoolingClientConnectionManager();
    connManager.setMaxTotal(getMaxTotalConnections());
    connManager.setDefaultMaxPerRoute(getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connManager, params);
    getLogger().info("Starting the HTTP client");
}

From source file:org.factor45.jhcb.benchmark.ApacheBenchmark.java

@Override
protected void setup() {
    super.setup();

    HttpParams params = new BasicHttpParams();
    params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    ConnManagerParams.setMaxTotalConnections(params, 10);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    this.client = new DefaultHttpClient(cm, params);
}

From source file:org.hydracache.server.httpd.HttpParamsFactory.java

public HttpParams create() {
    HttpParams httpParams = new BasicHttpParams();

    httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
    httpParams.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, socketBufferSize);
    httpParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    httpParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    httpParams.setParameter(CoreProtocolPNames.ORIGIN_SERVER, ORIGIN_SERVER_NAME);

    return httpParams;
}

From source file:com.jrodeo.queue.messageset.provider.TestHttpClient5.java

public TestHttpClient5() {
    super();//  ww  w .ja  v  a2 s  . co  m
    HttpParams params = new SyncBasicHttpParams();
    params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 15000);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    this.mgr = new PoolingClientConnectionManager(schemeRegistry);
    this.httpclient = new DefaultHttpClient(this.mgr, params);
    this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

        public boolean retryRequest(final IOException exception, int executionCount,
                final HttpContext context) {
            return false;
        }

    });
}

From source file:org.apache.hadoop.gateway.jetty.SslSocketTest.java

@Ignore
@Test/*from   w w  w  .j  a  v a  2 s.c  om*/
public void testSsl() throws IOException, InterruptedException {
    SslServer server = new SslServer();
    Thread thread = new Thread(server);
    thread.start();
    server.waitUntilReady();

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

    SSLSocketFactory sslsocketfactory = SSLSocketFactory.getSocketFactory();
    SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(params);

    sslsocket.connect(new InetSocketAddress("localhost", 9999));

    OutputStream outputstream = sslsocket.getOutputStream();
    OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
    BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);

    bufferedwriter.write("HELLO\n");
    bufferedwriter.flush();
}

From source file:com.example.dailyphoto.oath.EasyHttpClient.java

@Override
protected ClientConnectionManager createClientConnectionManager() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HTTP_PORT));
    registry.register(new Scheme("https", new EasySSLSocketFactory(), HTTPS_PORT));
    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);

    return manager;
}