Example usage for org.apache.http.params HttpProtocolParams setUserAgent

List of usage examples for org.apache.http.params HttpProtocolParams setUserAgent

Introduction

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

Prototype

public static void setUserAgent(HttpParams httpParams, String str) 

Source Link

Usage

From source file:com.gft.unity.android.AndroidIO.java

private HttpEntityEnclosingRequestBase buildWebRequest(IORequest request, IOService service,
        String requestUriString, String requestMethod) throws UnsupportedEncodingException, URISyntaxException {

    HttpEntityEnclosingRequestBase httpRequest = new HttpAppverse(new URI(requestUriString), requestMethod);

    /*************//from www.j a  v  a2  s.co  m
     * adding content as entity, for request methods != GET
     *************/
    if (!requestMethod.equalsIgnoreCase(RequestMethod.GET.toString())) {
        if (request.getContent() != null && request.getContent().length() > 0) {
            httpRequest.setEntity(new StringEntity(request.getContent(), HTTP.UTF_8));
        }
    }

    /*************
     * CONTENT TYPE
     *************/
    String contentType = contentTypes.get(service.getType()).toString();
    if (request.getContentType() != null) {
        contentType = request.getContentType();

    }
    httpRequest.setHeader("Content-Type", contentType);

    /*************
     * CUSTOM HEADERS HANDLING
     *************/
    if (request.getHeaders() != null && request.getHeaders().length > 0) {
        for (IOHeader header : request.getHeaders()) {
            httpRequest.setHeader(header.getName(), header.getValue());
        }
    }

    /*************
     * COOKIES HANDLING
     *************/
    if (request.getSession() != null && request.getSession().getCookies() != null
            && request.getSession().getCookies().length > 0) {
        StringBuffer buffer = new StringBuffer();
        IOCookie[] cookies = request.getSession().getCookies();
        for (int i = 0; i < cookies.length; i++) {
            IOCookie cookie = cookies[i];
            buffer.append(cookie.getName());
            buffer.append("=");
            buffer.append(cookie.getValue());
            if (i + 1 < cookies.length) {
                buffer.append(" ");
            }
        }
        httpRequest.setHeader("Cookie", buffer.toString());
    }

    /*************
     * DEFAULT HEADERS
     *************/
    httpRequest.setHeader("Accept", contentType); // Accept header should be the same as the request content type used (could be override by the request, or use the service default)
    // httpRequest.setHeader("content-length",
    // String.valueOf(request.getContentLength()));
    httpRequest.setHeader("keep-alive", String.valueOf(false));

    // TODO: set conn timeout ???

    /*************
     * setting user-agent
     *************/
    IOperatingSystem system = (IOperatingSystem) AndroidServiceLocator.GetInstance()
            .GetService(AndroidServiceLocator.SERVICE_TYPE_SYSTEM);
    HttpProtocolParams.setUserAgent(httpClient.getParams(), system.GetOSUserAgent());

    return httpRequest;
}

From source file:org.jets3t.service.utils.RestUtils.java

/**
 * Default Http parameters got from the DefaultHttpClient implementation.
 *
 * @return/*  w  w w. ja  v a2s . c o m*/
 * Default HTTP connection parameters
 */
public static HttpParams createDefaultHttpParams() {
    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // determine the release version from packaged version info
    final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client",
            HttpClient.class.getClassLoader());
    final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
    HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/" + release + " (java 1.5)");

    return params;
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

private @Nonnull HttpClient getClient() throws CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new CloudException("No context was provided for this request");
    }//from  w  w  w .  j a  v a2 s. c  om
    String endpoint = ctx.getEndpoint();
    boolean ssl = (endpoint != null && 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, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    return new DefaultHttpClient(params);
}

From source file:org.dasein.cloud.zimory.ZimoryMethod.java

private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new NoContextException();
    }/*  www .  j av  a 2  s .co m*/

    boolean ssl = uri.getScheme().startsWith("https");
    int targetPort = uri.getPort();

    if (targetPort < 1) {
        targetPort = (ssl ? 443 : 80);
    }
    HttpParams params = new BasicHttpParams();

    SchemeRegistry registry = new SchemeRegistry();

    try {
        registry.register(
                new Scheme(ssl ? "https" : "http", targetPort, new X509SSLSocketFactory(new X509Store(ctx))));
    } catch (KeyManagementException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new InternalException(e);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        throw new InternalException(e);
    }

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);

    return new DefaultHttpClient(ccm, params);
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Returns the preconfigured http client,
 * using CertificateVerificationService, timeouts, user-agent,
 * hostname verifier, proxy settings are used from global java settings,
 * if protected site is hit asks for credentials
 * using util.swing.AuthenticationWindow.
 * @param usernamePropertyName the property to use to retrieve/store
 * username value if protected site is hit, for username
 * ConfigurationService service is used.
 * @param passwordPropertyName the property to use to retrieve/store
 * password value if protected site is hit, for password
 * CredentialsStorageService service is used.
 * @param credentialsProvider if not null provider will bre reused
 * in the new client//from www  . j  a v a 2  s. co m
 * @param address the address we will be connecting to
 */
public static DefaultHttpClient getHttpClient(String usernamePropertyName, String passwordPropertyName,
        final String address, CredentialsProvider credentialsProvider) throws IOException {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(ClientPNames.MAX_REDIRECTS, MAX_REDIRECTS);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    HttpProtocolParams.setUserAgent(httpClient.getParams(),
            System.getProperty("sip-communicator.application.name") + "/"
                    + System.getProperty("sip-communicator.version"));

    SSLContext sslCtx;
    try {
        sslCtx = HttpUtilActivator.getCertificateVerificationService()
                .getSSLContext(HttpUtilActivator.getCertificateVerificationService().getTrustManager(address));
    } catch (GeneralSecurityException e) {
        throw new IOException(e.getMessage());
    }

    // note to any reviewer concerned about ALLOW_ALL_HOSTNAME_VERIFIER:
    // the SSL context obtained from the certificate service takes care of
    // certificate validation
    try {
        Scheme sch = new Scheme("https", 443, new SSLSocketFactoryEx(sslCtx));
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Throwable t) {
        logger.error("Error creating ssl socket factory", t);
    }

    // set proxy from default jre settings
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    if (credentialsProvider == null)
        credentialsProvider = new HTTPCredentialsProvider(usernamePropertyName, passwordPropertyName);
    httpClient.setCredentialsProvider(credentialsProvider);

    // enable retry connecting with default retry handler
    // when connecting has prompted for authentication
    // connection can be disconnected nefore user answers and
    // we need to retry connection, using the credentials provided
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    return httpClient;
}

From source file:com.lgallardo.youtorrentcontroller.JSONParser.java

public String getNewCookie() throws JSONParserStatusCodeException {

    String url = "login";

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }/* www. java  2s. c om*/

    String cookieString = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(hostname, port, protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        //            AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        //
        //            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        //
        //            httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        HttpPost httpget = new HttpPost(url);

        //            // In order to pass the username and password we must set the pair name value

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        nvps.add(new BasicNameValuePair("username", this.username));
        nvps.add(new BasicNameValuePair("password", this.password));

        httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse response = httpclient.execute(targetHost, httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode == 200) {

            // Save cookie
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();

            if (!cookies.isEmpty()) {
                cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue() + "; domain="
                        + cookies.get(0).getDomain();
                cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue();
            }

        }

        if (entity != null) {
            entity.consumeContent();
        }

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();

    } catch (Exception e) {

        Log.e("Debug", "Exception " + e.toString());
    }

    if (cookieString == null) {
        cookieString = "";
    }
    return cookieString;

}

From source file:com.mike.aframe.http.KJHttp.java

/**
 * ?httpClient// w w w  .  j a  v a  2 s .c  o m
 */
private void initHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, config.getConnectTimeOut());
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(config.getMaxConnections()));
    ConnManagerParams.setMaxTotalConnections(httpParams, config.getMaxConnections());

    HttpConnectionParams.setSoTimeout(httpParams, config.getConnectTimeOut());
    HttpConnectionParams.setConnectionTimeout(httpParams, config.getConnectTimeOut());
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, config.getSocketBuffer());

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, "KJLibrary");

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }

            for (Entry<String, String> entry : config.getHeader().entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });
    threadPool = (ThreadPoolExecutor) KJThreadExecutors.newCachedThreadPool();
    httpClient.setHttpRequestRetryHandler(new RetryHandler(config.getReadTimeout()));
    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
}

From source file:com.vuze.android.remote.AndroidUtils.java

public static boolean readURL(String uri, ByteArrayBuffer bab, byte[] startsWith)
        throws IllegalArgumentException {

    BasicHttpParams basicHttpParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");
    DefaultHttpClient httpclient = new DefaultHttpClient(basicHttpParams);

    // Prepare a request object
    HttpRequestBase httpRequest = new HttpGet(uri);

    // Execute the request
    HttpResponse response;/*from  w  w  w  . j av a 2s  .c om*/

    try {
        response = httpclient.execute(httpRequest);

        HttpEntity entity = response.getEntity();
        if (entity != null) {

            // A Simple JSON Response Read
            InputStream is = entity.getContent();
            return readInputStreamIfStartWith(is, bab, startsWith);
        }

    } catch (Exception e) {
        VuzeEasyTracker.getInstance().logError(e);
    }

    return false;
}

From source file:com.vuze.android.remote.AndroidUtils.java

public static void copyUrlToFile(String uri, File outFile) throws ClientProtocolException, IOException {

    BasicHttpParams basicHttpParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");
    DefaultHttpClient httpclient = new DefaultHttpClient(basicHttpParams);

    // Prepare a request object
    HttpRequestBase httpRequest = new HttpGet(uri);

    // Execute the request
    HttpResponse response;//w w w . jav  a 2  s  .c o  m

    response = httpclient.execute(httpRequest); // HttpHostConnectException

    HttpEntity entity = response.getEntity();
    if (entity != null) {

        // A Simple JSON Response Read
        InputStream is = entity.getContent();
        copyFile(is, outFile, true); // FileNotFoundException
    }
}

From source file:cn.org.eshow.framwork.http.AbHttpClient.java

/**
 * HTTP??//ww w. j a va  2 s.  co m
 * @return
 */
public BasicHttpParams getHttpParams() {

    BasicHttpParams httpParams = new BasicHttpParams();

    // ?
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(30);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
    // ?1
    ConnManagerParams.setTimeout(httpParams, mTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    // ??
    HttpConnectionParams.setSoTimeout(httpParams, mTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, mTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, userAgent);
    //?
    HttpClientParams.setRedirecting(httpParams, false);
    HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY);
    httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
    return httpParams;

}