Java Code Examples for org.apache.http.params.HttpProtocolParams#setUserAgent()

The following examples show how to use org.apache.http.params.HttpProtocolParams#setUserAgent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetworkHelper.java    From fanfouapp-opensource with Apache License 2.0 6 votes vote down vote up
private static final HttpParams createHttpParams() {
    final HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ConnManagerParams.setTimeout(params, NetworkHelper.SOCKET_TIMEOUT_MS);
    HttpConnectionParams.setConnectionTimeout(params,
            NetworkHelper.CONNECTION_TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(params,
            NetworkHelper.SOCKET_TIMEOUT_MS);

    ConnManagerParams.setMaxConnectionsPerRoute(params,
            new ConnPerRouteBean(NetworkHelper.MAX_TOTAL_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(params,
            NetworkHelper.MAX_TOTAL_CONNECTIONS);

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params,
            NetworkHelper.SOCKET_BUFFER_SIZE);
    HttpClientParams.setRedirecting(params, false);
    HttpProtocolParams.setUserAgent(params, "FanFou for Android/"
            + AppContext.appVersionName);
    return params;
}
 
Example 2
Source File: ApacheClient.java    From android-lite-http with Apache License 2.0 5 votes vote down vote up
/**
 * initialize HttpParams , initialize settings such as total connextions,timeout ...
 */
private BasicHttpParams createHttpParams() {
    BasicHttpParams params = new BasicHttpParams();
    ConnManagerParams.setTimeout(params, DEFAULT_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(DEFAULT_MAX_CONN_PER_ROUT));
    ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONN_TOTAL);
    HttpConnectionParams.setTcpNoDelay(params, TCP_NO_DELAY);
    HttpConnectionParams.setConnectionTimeout(params, DEFAULT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, DEFAULT_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, DEFAULT_BUFFER_SIZE);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, userAgent);
    // settingOthers(params);
    return params;
}
 
Example 3
Source File: ClientBuilder.java    From hbc with Apache License 2.0 5 votes vote down vote up
public BasicClient build() {
  HttpParams params = new BasicHttpParams();
  if (proxyHost != null) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
  }
  HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  HttpProtocolParams.setUserAgent(params, USER_AGENT);
  HttpConnectionParams.setSoTimeout(params, socketTimeoutMillis);
  HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMillis);
  return new BasicClient(name, hosts, endpoint, auth, enableGZip, processor, reconnectionManager,
          rateTracker, executorService, eventQueue, params, schemeRegistry);
}
 
Example 4
Source File: DownloadPstTask.java    From Presentation with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPreExecute() {
    mHttpClient = new DefaultHttpClient();

    HttpParams httpParams = mHttpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, Huaban.TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, Huaban.TIMEOUT);
    HttpProtocolParams.setUserAgent(httpParams, Huaban.USER_AGENT);

    mListener.onStart();
}
 
Example 5
Source File: ConfigurationService.java    From RoboZombie with Apache License 2.0 5 votes vote down vote up
/**
 * <p>The <i>out-of-the-box</i> configuration for an instance of {@link HttpClient} which will be used for 
 * executing all endpoint requests. Below is a detailed description of all configured properties.</p> 
 * <br>
 * <ul>
 * <li>
 * <p><b>HttpClient</b></p>
 * <br>
 * <p>It registers two {@link Scheme}s:</p>
 * <br>
 * <ol>
 * 	<li><b>HTTP</b> on port <b>80</b> using sockets from {@link PlainSocketFactory#getSocketFactory}</li>
 * 	<li><b>HTTPS</b> on port <b>443</b> using sockets from {@link SSLSocketFactory#getSocketFactory}</li>
 * </ol>
 * 
 * <p>It uses a {@link ThreadSafeClientConnManager} with the following parameters:</p>
 * <br>
 * <ol>
 * 	<li><b>Redirecting:</b> enabled</li>
 * 	<li><b>Connection Timeout:</b> 30 seconds</li>
 * 	<li><b>Socket Timeout:</b> 30 seconds</li>
 * 	<li><b>Socket Buffer Size:</b> 12000 bytes</li>
 * 	<li><b>User-Agent:</b> via <code>System.getProperty("http.agent")</code></li>
 * </ol>
 * </li>
 * </ul>
 * @return the instance of {@link HttpClient} which will be used for request execution
 * <br><br>
 * @since 1.3.0
 */
@Override
public Configuration getDefault() {
	
	return new Configuration() {

		@Override
		public HttpClient httpClient() {
			
			try {
			
				HttpParams params = new BasicHttpParams();
				HttpClientParams.setRedirecting(params, true);
				HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
				HttpConnectionParams.setSoTimeout(params, 30 * 1000);
				HttpConnectionParams.setSocketBufferSize(params, 12000);
		        HttpProtocolParams.setUserAgent(params, System.getProperty("http.agent"));
		        
		        SchemeRegistry schemeRegistry = new SchemeRegistry();
		        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		        ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

		        return new DefaultHttpClient(manager, params);
			}
			catch(Exception e) {
				
				throw new ConfigurationFailedException(e);
			}
		}
	};
}
 
Example 6
Source File: HttpClientConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void configureUserAgent(DefaultHttpClient httpClient) {
    HttpProtocolParams.setUserAgent(httpClient.getParams(), UriResource.getUserAgentString());
}
 
Example 7
Source File: HttpClientConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void configureUserAgent(DefaultHttpClient httpClient) {
    HttpProtocolParams.setUserAgent(httpClient.getParams(), UriResource.getUserAgentString());
}
 
Example 8
Source File: HttpClientConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void configureUserAgent(DefaultHttpClient httpClient) {
    HttpProtocolParams.setUserAgent(httpClient.getParams(), UriResource.getUserAgentString());
}
 
Example 9
Source File: ApacheHttpProvider.java    From OCR-Equation-Solver with MIT License 4 votes vote down vote up
public void setUserAgent(String agent) {
    HttpProtocolParams.setUserAgent(params, agent);
}
 
Example 10
Source File: HttpRequestHelper.java    From YiBo with Apache License 2.0 4 votes vote down vote up
private static synchronized HttpClient createHttpClient(HttpConfig config) {
	if (config == null) {
		return null;
	}

	if (connectionManager == null) {
		connectionManager = createConnectionManager();
	}

	HttpParams httpParams = new BasicHttpParams();

	if (config.getHttpConnectionTimeout() > 0) {
		httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
			config.getHttpConnectionTimeout());
	}
	if (config.getHttpReadTimeout() > 0) {
		httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getHttpReadTimeout());
	}
	// 设置cookie策略
    httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
			
	// 设置http.protocol.expect-continue参数为false,即不使用Expect:100-Continue握手,
	// 因为如果服务器不支持HTTP 1.1,则会导致HTTP 417错误。
	HttpProtocolParams.setUseExpectContinue(httpParams, false);
	// 设置User-Agent
	HttpProtocolParams.setUserAgent(httpParams, config.getUserAgent());
	// 设置HTTP版本为 HTTP 1.1
	HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

	DefaultHttpClient httpClient = new LibHttpClient(connectionManager, httpParams);

	updateProxySetting(config, httpClient);

	if (config.isUseGzip()) {
		httpClient.addRequestInterceptor(new GzipRequestInterceptor());
		httpClient.addResponseInterceptor(new GzipResponseInterceptor());
	}
	if (config.getHttpRetryCount() > 0) {
		HttpRequestRetryHandler retryHandler =
			new DefaultHttpRequestRetryHandler(config.getHttpRetryCount(), true);
		httpClient.setHttpRequestRetryHandler(retryHandler);
	}

	return httpClient;
}
 
Example 11
Source File: RuntimeHttpUtils.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches a file from the URI given and returns an input stream to it.
 *
 * @param uri the uri of the file to fetch
 * @param config optional configuration overrides
 * @return an InputStream containing the retrieved data
 * @throws IOException on error
 */
@SuppressWarnings("deprecation")
public static InputStream fetchFile(
        final URI uri,
        final ClientConfiguration config) throws IOException {

    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(
            httpClientParams, getUserAgent(config, null));

    HttpConnectionParams.setConnectionTimeout(
            httpClientParams, getConnectionTimeout(config));
    HttpConnectionParams.setSoTimeout(
            httpClientParams, getSocketTimeout(config));

    DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams);

    if (config != null) {
        String proxyHost = config.getProxyHost();
        int proxyPort = config.getProxyPort();

        if (proxyHost != null && proxyPort > 0) {

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpclient.getParams().setParameter(
                    ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (config.getProxyUsername() != null
                && config.getProxyPassword() != null) {

                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(config.getProxyUsername(),
                                          config.getProxyPassword(),
                                          config.getProxyWorkstation(),
                                          config.getProxyDomain()));
            }
        }
    }

    HttpResponse response = httpclient.execute(new HttpGet(uri));

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Error fetching file from " + uri + ": "
                              + response);
    }

    return new HttpClientWrappingInputStream(
            httpclient,
            response.getEntity().getContent());
}
 
Example 12
Source File: HttpUtils.java    From android-open-project-demo with Apache License 2.0 4 votes vote down vote up
public HttpUtils configUserAgent(String userAgent) {
    HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
    return this;
}
 
Example 13
Source File: AsyncHttpClient.java    From letv with Apache License 2.0 4 votes vote down vote up
public void setUserAgent(String userAgent) {
    HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
}
 
Example 14
Source File: TestTwitterSocket.java    From albert with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	  OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
				Constants.ConsumerKey,
				Constants.ConsumerSecret);
	  consumer.setTokenWithSecret(Constants.AccessToken, Constants.AccessSecret);
	  
	  
    HttpParams params = new BasicHttpParams();
    // HTTP 协议的版本,1.1/1.0/0.9
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // 字符集
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    // 伪装的浏览器类型
    // IE7 是 
    // Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)
    //
    // Firefox3.03
    // Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3
    //
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("127.0.0.1", 1080);
    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
    try {
      String[] targets = { "https://www.twitter.com"};
      for (int i = 0; i < targets.length; i++) {
        if (!conn.isOpen()) {
          Socket socket = new Socket(host.getHostName(), host.getPort());
          conn.bind(socket, params);
        }
        
	  
        BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
//        consumer.sign(request);
        
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);
        // 返回码
        System.out.println("<< Response: " + response.getStatusLine());
        // 返回的文件头信息
//        Header[] hs = response.getAllHeaders();
//        for (Header h : hs) {
//          System.out.println(h.getName() + ":" + h.getValue());
//        }
        // 输出主体信息
//        System.out.println(EntityUtils.toString(response.getEntity()));
        
        HttpEntity entry = response.getEntity();
        StringBuffer sb = new StringBuffer();
  	  if(entry != null)
  	  {
  	    InputStreamReader is = new InputStreamReader(entry.getContent());
  	    BufferedReader br = new BufferedReader(is);
  	    String str = null;
  	    while((str = br.readLine()) != null)
  	    {
  	     sb.append(str.trim());
  	    }
  	    br.close();
  	  }
  	  System.out.println(sb.toString());
  	  
        System.out.println("==============");
        if (!connStrategy.keepAlive(response, context)) {
          conn.close();
        } else {
          System.out.println("Connection kept alive...");
        }
      }
    } finally {
      conn.close();
    }
  }
 
Example 15
Source File: HttpClientConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void configureUserAgent(DefaultHttpClient httpClient) {
    HttpProtocolParams.setUserAgent(httpClient.getParams(), UriResource.getUserAgentString());
}
 
Example 16
Source File: AsyncHttpClient.java    From Libraries-for-Android-Developers with MIT License 2 votes vote down vote up
/**
 * Sets the User-Agent header to be sent with each request. By default, "Android Asynchronous
 * Http Client/VERSION (http://loopj.com/android-async-http/)" is used.
 *
 * @param userAgent the string to use in the User-Agent header.
 */
public void setUserAgent(String userAgent) {
    HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
}
 
Example 17
Source File: AsyncHttpClient.java    From sealtalk-android with MIT License 2 votes vote down vote up
/**
 * Sets the User-Agent header to be sent with each request. By default, "Android Asynchronous
 * Http Client/VERSION (http://loopj.com/android-async-http/)" is used.
 *
 * @param userAgent the string to use in the User-Agent header.
 */
public void setUserAgent(String userAgent) {
    HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
}
 
Example 18
Source File: AsyncHttpClient.java    From Android-Basics-Codes with Artistic License 2.0 2 votes vote down vote up
/**
 * Sets the User-Agent header to be sent with each request. By default, "Android Asynchronous
 * Http Client/VERSION (http://loopj.com/android-async-http/)" is used.
 *
 * @param userAgent the string to use in the User-Agent header.
 */
public void setUserAgent(String userAgent) {
    HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
}
 
Example 19
Source File: AsyncHttpClient.java    From Mobike with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the User-Agent header to be sent with each request. By default, "Android Asynchronous
 * Http Client/VERSION (http://loopj.com/android-async-http/)" is used.
 *
 * @param userAgent the string to use in the User-Agent header.
 */
public void setUserAgent(String userAgent) {
    HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
}
 
Example 20
Source File: AsyncHttpClient.java    From Android-Basics-Codes with Artistic License 2.0 2 votes vote down vote up
/**
 * Sets the User-Agent header to be sent with each request. By default, "Android Asynchronous
 * Http Client/VERSION (http://loopj.com/android-async-http/)" is used.
 *
 * @param userAgent the string to use in the User-Agent header.
 */
public void setUserAgent(String userAgent) {
    HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
}