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: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.tiaoin.crawl.plugin.util.PageFetcherImpl.java

/**
 * client?Header?Cookie//from   w  ww . ja  v a2  s  . c o  m
 * @param aconfig
 * @param cookies
 */
public void init(Site site) {
    //System.out.println(site.toString());
    if (null != site.getHeaders() && site.getHeaders().getHeader() != null) {
        for (com.tiaoin.crawl.core.xml.Header header : site.getHeaders().getHeader()) {
            this.addHeader(header.getName(), header.getValue());
        }
    }
    if (null != site.getCookies() && site.getCookies().getCookie() != null) {
        for (com.tiaoin.crawl.core.xml.Cookie cookie : site.getCookies().getCookie()) {
            this.addCookie(cookie.getName(), cookie.getValue(), cookie.getHost(), cookie.getPath());
        }
    }

    //HTTP?
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

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

    if (config.isIncludeHttpsPages())
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    httpClient = new DefaultHttpClient(connectionManager, params);
    httpClient.getParams().setIntParameter("http.socket.timeout", 15000);
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    //?
    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    //?GZIP
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });
}

From source file:com.wso2telco.proxy.entity.ServerInitiatedServiceEndpoints.java

private String getAuthCode(String url) {
    String code = null;/*w  ww  . j  av a 2  s .c  om*/
    while (code == null) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpParams params = new BasicHttpParams();
        params.setParameter("http.protocol.handle-redirects", false);
        httpGet.setParams(params);

        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
        } catch (IOException e) {
            log.info("Error while handling httpClient redirection. ", e);
            return null;
        }
        if (httpResponse.getStatusLine().getStatusCode() == 302) {
            url = httpResponse.getFirstHeader("location").getValue();
            if (url.contains("code=")) {
                try {
                    code = getParamValueFromURL("code", url);
                    return code;
                } catch (URISyntaxException e) {
                    log.info(url + " - URL is malformed ", e);
                    return null;
                }
            }
        } else {
            break;
        }
    }
    return null;
}

From source file:org.geomajas.gwt2.example.base.server.mvc.AjaxProxyController.java

@RequestMapping(value = "/")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");

    HttpClient client = new DefaultHttpClient();
    try {//from www  .j a v a2 s .  c om
        HttpRequestBase proxyRequest;

        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!paramName.equalsIgnoreCase("url")) {
                    url = addParam(url, paramName, request.getParameter(paramName));
                }
            }

            proxyRequest = new HttpGet(url);
        } else if ("POST".equals(request.getMethod())) {
            proxyRequest = new HttpPost(url);

            // Set any eventual parameters that came with our original
            HttpParams params = new BasicHttpParams();
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!"url".equalsIgnoreCase("url")) {
                    params.setParameter(paramName, request.getParameter(paramName));
                }
            }
            proxyRequest.setParams(params);
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Execute the method
        HttpResponse proxyResponse = client.execute(proxyRequest);

        // Set the content type, as it comes from the server
        Header[] headers = proxyResponse.getAllHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }

        // Write the body, flush and close
        proxyResponse.getEntity().writeTo(response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.mobicents.xcap.client.impl.XcapClientImpl.java

/**
 * /*from  w  w  w .  j a  v  a 2s.  c o m*/
 */
public XcapClientImpl() {
    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);
    params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    this.client = new DefaultHttpClient(new ThreadSafeClientConnManager(schemeRegistry), params);
    this.client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

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

    });
    client.setCredentialsProvider(credentialsProvider);
}

From source file:org.cm.podd.report.service.DataSubmitService.java

private boolean submitImage(ReportImage reportImage, String reportGuid)
        throws URISyntaxException, IOException, JSONException {

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);
    boolean success = false;

    try {//from ww  w .ja  v a2 s. co  m

        String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL);

        URI http = new URI(serverUrl + "/reportImages/");
        Log.i(TAG, "submit report image url=" + http.toURL());

        HttpPost post = new HttpPost(http);
        post.setHeader("Content-type", "application/json");
        post.setHeader("Authorization", "Token " + sharedPrefUtil.getAccessToken());

        String note = reportImage.getNote();
        if (note == null) {
            note = "";
        }

        JSONObject data = new JSONObject();
        data.put("note", note);
        data.put("reportGuid", reportGuid);
        data.put("guid", reportImage.getGuid());
        data.put("imageUrl", S3IMAGE_URL_PREFIX + reportImage.getGuid());
        data.put("thumbnailUrl", S3IMAGE_URL_PREFIX + reportImage.getGuid() + "-thumbnail");

        post.setEntity(new StringEntity(data.toString(), HTTP.UTF_8));

        HttpResponse response;
        response = client.execute(post);
        HttpEntity entity = response.getEntity();

        int statusCode = response.getStatusLine().getStatusCode();
        Log.d(TAG, "status code=" + statusCode);
        success = statusCode == 201;
        // Detect server complaints
        entity.consumeContent();

        // delete cache file if success
        if (success) {
            if (reportImage.getImageUri().startsWith(FileUtil.TEMP_IMAGE_PREFIX)) {
                File file = new File(reportImage.getImageUri());
                file.delete();
            }
        }

    } finally {
        client.getConnectionManager().shutdown();
    }
    return success;

}

From source file:com.ichi2.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;//from   w ww . ja  v a  2 s . c  o m
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // compression flag and session key as post vars
        buf.write(bdry + "\r\n");
        buf.write("Content-Disposition: form-data; name=\"c\"\r\n\r\n" + (comp != 0 ? 1 : 0) + "\r\n");
        if (hkey) {
            buf.write(bdry + "\r\n");
            buf.write("Content-Disposition: form-data; name=\"k\"\r\n\r\n" + mHKey + "\r\n");
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersion());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java

public LDClient(ClientConfiguration config) {
    log.info("Initialising Linked Data Client Service ...");

    this.config = config;

    endpoints = new ArrayList<>();
    for (Endpoint endpoint : defaultEndpoints) {
        endpoints.add(endpoint);//from ww w .  j  ava  2  s .  c  o  m
    }
    endpoints.addAll(config.getEndpoints());

    Collections.sort(endpoints);
    if (log.isInfoEnabled()) {
        for (Endpoint endpoint : endpoints) {
            log.info("- LDClient Endpoint: {}", endpoint.getName());
        }
    }

    providers = new ArrayList<>();
    for (DataProvider provider : defaultProviders) {
        providers.add(provider);
    }
    providers.addAll(config.getProviders());
    if (log.isInfoEnabled()) {
        for (DataProvider provider : providers) {
            log.info("- LDClient Provider: {}", provider.getName());
        }
    }

    retrievalSemaphore = new Semaphore(config.getMaxParallelRequests());

    if (config.getHttpClient() != null) {
        log.debug("Using HttpClient provided in the configuration");
        this.client = config.getHttpClient();
    } else {
        log.debug("Creating default HttpClient based on the configuration");

        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Marmotta LDClient");

        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
        httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

        httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);

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

        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", 443, sf));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(20);
        cm.setDefaultMaxPerRoute(10);

        DefaultHttpClient client = new DefaultHttpClient(cm, httpParams);
        client.setRedirectStrategy(new LMFRedirectStrategy());
        client.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler());
        idleConnectionMonitorThread = new IdleConnectionMonitorThread(client.getConnectionManager());
        idleConnectionMonitorThread.start();

        this.client = client;
    }
}

From source file:com.hichinaschool.flashcards.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;// w  ww.  j a v  a2 s .c o  m
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        HashMap<String, Object> vars = new HashMap<String, Object>();
        // compression flag and session key as post vars
        vars.put("c", comp != 0 ? 1 : 0);
        if (hkey) {
            vars.put("k", mHKey);
            vars.put("s", mSKey);
        }
        for (String key : vars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    vars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java

/**
 * @return A properly configured HTTP client instance
 */// w ww.j  a v  a 2  s .com
private HttpClient getClient() {
    // Set up client with proper timeout
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    return new DefaultHttpClient(params);
}