org.apache.http.params.HttpParams Java Examples

The following examples show how to use org.apache.http.params.HttpParams. 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 Project: hbc   Author: twitter   File: BasicClient.java    License: Apache License 2.0 6 votes vote down vote up
public BasicClient(String name, Hosts hosts, StreamingEndpoint endpoint, Authentication auth, boolean enableGZip, HosebirdMessageProcessor processor,
                   ReconnectionManager reconnectionManager, RateTracker rateTracker, ExecutorService executorService,
                   @Nullable BlockingQueue<Event> eventsQueue, HttpParams params, SchemeRegistry schemeRegistry) {
  Preconditions.checkNotNull(auth);
  HttpClient client;
  if (enableGZip) {
    client = new RestartableHttpClient(auth, enableGZip, params, schemeRegistry);
  } else {
    DefaultHttpClient defaultClient = new DefaultHttpClient(new PoolingClientConnectionManager(schemeRegistry), params);

    /** Set auth **/
    auth.setupConnection(defaultClient);
    client = defaultClient;
  }

  this.canRun = new AtomicBoolean(true);
  this.executorService = executorService;
  this.clientBase = new ClientBase(name, client, hosts, endpoint, auth, processor, reconnectionManager, rateTracker, eventsQueue);
}
 
Example #2
Source Project: quarkus-http   Author: quarkusio   File: HttpContinueAcceptingHandlerTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpContinueRejected() throws IOException {
    accept = false;
    String message = "My HTTP Request!";
    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter("http.getProtocol.wait-for-continue", Integer.MAX_VALUE);

    TestHttpClient client = new TestHttpClient();
    client.setParams(httpParams);
    try {
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        post.addHeader("Expect", "100-continue");
        post.setEntity(new StringEntity(message));

        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.EXPECTATION_FAILED, result.getStatusLine().getStatusCode());
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #3
Source Project: onboard   Author: sercxtyf   File: ApiProxyServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws ServletException {
    String doLogStr = getConfigParam(P_LOG);
    if (doLogStr != null) {
        this.doLog = Boolean.parseBoolean(doLogStr);
    }

    String doForwardIPString = getConfigParam(P_FORWARDEDFOR);
    if (doForwardIPString != null) {
        this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
    }

    initTarget();// sets target*

    HttpParams hcParams = new BasicHttpParams();
    hcParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class);
    proxyClient = createHttpClient(hcParams);
}
 
Example #4
Source Project: FoodOrdering   Author: yangxch   File: NetWorkTool.java    License: Apache License 2.0 6 votes vote down vote up
public static String getContent(String url) throws Exception {
    StringBuilder sb = new StringBuilder();

    HttpClient client = new DefaultHttpClient();
    HttpParams httpParams = (HttpParams) client.getParams();
    // 设置网络超时参数
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    HttpResponse response = client.execute(new HttpGet(url));
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                entity.getContent(), "GBK"), 8192);
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
    }
    return sb.toString();
}
 
Example #5
Source Project: carbon-apimgt   Author: wso2   File: HttpLoadTestClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    SchemeRegistry supportedSchemes = new SchemeRegistry();
    SocketFactory sf = PlainSocketFactory.getSocketFactory();
    supportedSchemes.register(new Scheme("http", sf, 80));
    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(supportedSchemes);
    connManager.setDefaultMaxPerRoute(1000);
    DefaultHttpClient client = new DefaultHttpClient(connManager);
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
    //test API call
    long t1 = System.currentTimeMillis();
    testEndpoint(client,apiEndpoint);
    long t2 = System.currentTimeMillis();
    timeElapsedForAPICall = t2 - t1;


}
 
Example #6
Source Project: Libraries-for-Android-Developers   Author: eoecn   File: MySSLSocketFactory.java    License: MIT License 6 votes vote down vote up
/**
    * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
    * 
    * @param keyStore
    * @return
    */
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
	
    try {
	    SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
	    SchemeRegistry registry = new SchemeRegistry();
	    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
	    registry.register(new Scheme("https", sf, 443));

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
 
Example #7
Source Project: letv   Author: JackChan1999   File: ImmersionHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
public HttpParams getParams() {
    try {
        DefaultHttpClient defaultHttpClient = this.bнн043Dн043Dн;
        if (((b04170417041704170417З + b0417ЗЗЗЗ0417) * b04170417041704170417З) % bЗ0417ЗЗЗ0417 != bЗЗЗЗЗ0417) {
            b04170417041704170417З = b04170417ЗЗЗ0417();
            bЗЗЗЗЗ0417 = 88;
        }
        try {
            return defaultHttpClient.getParams();
        } catch (Exception e) {
            throw e;
        }
    } catch (Exception e2) {
        throw e2;
    }
}
 
Example #8
Source Project: neembuu-uploader   Author: Neembuu-Uploader   File: CheckUser.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void getCanCustomizeNormalizing(UserSetPriv usp) {
    boolean canCustomizeNormalizing = true;
    String normalization = ".neembuu";
    HttpParams params = new BasicHttpParams();
    params.setParameter(
            "http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    HttpClient httpclient = NUHttpClient.getHttpClient();
    HttpGet httpget = new HttpGet("http://neembuu.com/uploader/api/user.xml?userid="+UserImpl.I().uid());
    NULogger.getLogger().info("Checking for user priviledges ...");
    try {
        HttpResponse response = httpclient.execute(httpget);
        String respxml = EntityUtils.toString(response.getEntity());
        canCustomizeNormalizing = getCanCustomizeNormalizingFromXml(respxml);
        normalization = getNormalization(respxml);
        NULogger.getLogger().log(Level.INFO, "CanCustomizeNormalizing: {0}", canCustomizeNormalizing);
    } catch (Exception ex) {
        NULogger.getLogger().log(Level.INFO, "Exception while checking update\n{0}", ex);
    }
    usp.setCanCustomizeNormalizing(canCustomizeNormalizing);
    usp.setNormalization(normalization);
}
 
Example #9
Source Project: javabase   Author: ggj2010   File: GetClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 此处解释下MaxtTotal和DefaultMaxPerRoute的区别:
 * 1、MaxtTotal是整个池子的大小;
 * 2、DefaultMaxPerRoute是根据连接到的主机对MaxTotal的一个细分;比如:
 * MaxtTotal=400 DefaultMaxPerRoute=200
 * 而我只连接到http://sishuok.com时,到这个主机的并发最多只有200;而不是400;
 * 而我连接到http://sishuok.com 和 http://qq.com时,到每个主机的并发最多只有200;即加起来是400(但不能超过400);所以起作用的设置是DefaultMaxPerRoute。
 */
public HttpParams getHttpParams() {
    HttpParams params = new BasicHttpParams();
    // 设置连接超时时间
    Integer CONNECTION_TIMEOUT = 2 * 1000; // 设置请求超时2秒钟 根据业务调整
    Integer SO_TIMEOUT = 2 * 1000; // 设置等待数据超时时间2秒钟 根据业务调整
    // 定义了当从ClientConnectionManager中检索ManagedClientConnection实例时使用的毫秒级的超时时间
    // 这个参数期望得到一个java.lang.Long类型的值。如果这个参数没有被设置,默认等于CONNECTION_TIMEOUT,因此一定要设置
    Long CONN_MANAGER_TIMEOUT = 500L; // 该值就是连接不够用的时候等待超时时间,一定要设置,而且不能太大 ()

    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
    params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, CONN_MANAGER_TIMEOUT);
    // 在提交请求之前 测试连接是否可用
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
    return params;
}
 
Example #10
Source Project: galaxy-sdk-java   Author: XiaoMi   File: EMQClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
public static HttpClient generateHttpClient(final int maxTotalConnections,
                                            final int maxTotalConnectionsPerRoute, int connTimeout) {
  HttpParams params = new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params, maxTotalConnections);
  ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
    @Override
    public int getMaxForRoute(HttpRoute route) {
      return maxTotalConnectionsPerRoute;
    }
  });
  HttpConnectionParams
          .setConnectionTimeout(params, connTimeout);
  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(
          new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
  sslSocketFactory.setHostnameVerifier(SSLSocketFactory.
          ALLOW_ALL_HOSTNAME_VERIFIER);
  schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
  ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,
          schemeRegistry);
  return new DefaultHttpClient(conMgr, params);
}
 
Example #11
Source Project: android-project-wo2b   Author: benniaobuguai   File: HttpClientStack.java    License: Apache License 2.0 6 votes vote down vote up
@Override
   public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
           throws IOException, AuthFailureError {
       HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
       addHeaders(httpRequest, additionalHeaders);
       addHeaders(httpRequest, request.getHeaders());
       onPrepareRequest(httpRequest);
       HttpParams httpParams = httpRequest.getParams();
       int timeoutMs = request.getTimeoutMs();
       // TODO: Reevaluate this connection timeout based on more wide-scale
       // data collection and possibly different for wifi vs. 3G.
       // HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
       // HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
	/**
	 * ����ͬ������sql��ִ��ʱ��Ͳ���ʱ��̫��, ��ʱʱ��, ����Ϊ30,000����
	 */
	final int timeout = 30 * 1000;
	HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
	HttpConnectionParams.setSoTimeout(httpParams, timeout);
	
	return mClient.execute(httpRequest);
}
 
Example #12
Source Project: neembuu-uploader   Author: Neembuu-Uploader   File: CommonUploaderTasks.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * This private method will send statistics to the server.
 * Download Links or Delete Links will not be sent for privacy reasons.
 * 
 * These data are used for analysis and cleared periodically to avoid exceeding quota.
 * 
 * @param up 
 */
private static void sendStats(Uploader up) {
    try {
        String status = up.getStatus().getDefaultLocaleSpecificString();
        if (!status.startsWith("Upload")) {
            return;
        }

        String hostName = up.getHost();
        if(hostName.contains("|")){
            hostName = hostName.substring(hostName.indexOf("|"));
            hostName = "account " + hostName;
        }

        NULogger.getLogger().info("Sending statistics..");
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("version", pvp.getVersionForProgam() ) );
        formparams.add(new BasicNameValuePair("filename", up.getFileName()));
        formparams.add(new BasicNameValuePair("size", up.getSize()));
        formparams.add(new BasicNameValuePair("host", hostName));
        formparams.add(new BasicNameValuePair("status", status));
        formparams.add(new BasicNameValuePair("os", System.getProperty("os.name")));
        formparams.add(new BasicNameValuePair("locale", ulcp.getUserLanguageCode()
                /*NeembuuUploaderLanguages.getUserLanguageCode()*/));
        formparams.add(new BasicNameValuePair("uid", userP.getUserInstance().uidString()
                /*UserImpl.I().uidString()*/));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        HttpPost httppost = new HttpPost("http://neembuuuploader.sourceforge.net/insert.php");
        httppost.setEntity(entity);
        HttpParams params = new BasicHttpParams();
        params.setParameter(
                "http.useragent",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
        httppost.setParams(params);
        HttpClient httpclient = NUHttpClient.getHttpClient();
        EntityUtils.consume(httpclient.execute(httppost).getEntity());
    } catch (Exception ex) {
        NULogger.getLogger().log(Level.INFO, "Error while sending statistics\n{0}", ex);
    }
}
 
Example #13
Source Project: netcdf-java   Author: Unidata   File: TestSocketFactory.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Socket createSocket(HttpParams params) {
  // See if our test parameter is present
  Object o = params.getParameter("testtesttest");
  assert (o != null);
  return super.createSocket(params);
}
 
Example #14
Source Project: product-emm   Author: wso2-attic   File: HttpClientStack.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    onPrepareRequest(httpRequest);
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    return mClient.execute(httpRequest);
}
 
Example #15
Source Project: google-http-java-client   Author: googleapis   File: ApacheHttpTransport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of the Apache HTTP client that is used by the {@link
 * #ApacheHttpTransport()} constructor.
 *
 * @param socketFactory SSL socket factory
 * @param params HTTP parameters
 * @param proxySelector HTTP proxy selector to use {@link ProxySelectorRoutePlanner} or {@code
 *     null} for {@link DefaultHttpRoutePlanner}
 * @return new instance of the Apache HTTP client
 */
static DefaultHttpClient newDefaultHttpClient(
    SSLSocketFactory socketFactory, HttpParams params, ProxySelector proxySelector) {
  // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html
  SchemeRegistry registry = new SchemeRegistry();
  registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  registry.register(new Scheme("https", socketFactory, 443));
  ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
  DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
  defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
  if (proxySelector != null) {
    defaultHttpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));
  }
  return defaultHttpClient;
}
 
Example #16
Source Project: device-database   Author: android-database-best-practices   File: HttpClientStack.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    onPrepareRequest(httpRequest);
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    return mClient.execute(httpRequest);
}
 
Example #17
Source Project: LitePlayer   Author: qibin0506   File: HttpUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpParams getParams() {
	HttpParams params = new BasicHttpParams();
	HttpConnectionParams.setConnectionTimeout(params, 4000);
	HttpConnectionParams.setSoTimeout(params, 10000);
	ConnManagerParams.setTimeout(params, 4000);
	HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
	HttpProtocolParams.setUseExpectContinue(params, true);
	HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows NT 6.1; WOW64)" +
			" AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36");
	return params;
}
 
Example #18
Source Project: buddycloud-android   Author: buddycloud   File: BuddycloudHTTPHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpClient createHttpClient(Context context) {
	try {

		SchemeRegistry registry = new SchemeRegistry();
		SocketFactory socketFactory = createSecureSocketFactory();

		registry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		registry.register(new Scheme("https", socketFactory, 443));

		HttpParams connManagerParams = new BasicHttpParams();
		ConnManagerParams.setMaxTotalConnections(connManagerParams, 20);
		ConnManagerParams.setMaxConnectionsPerRoute(connManagerParams,
				new ConnPerRouteBean(20));

		ClientConnectionManager ccm = new ThreadSafeClientConnManager(
				connManagerParams, registry);

		DefaultHttpClient client = new DefaultHttpClient(ccm, null);
		client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(
				0, true));

		return client;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #19
Source Project: blog   Author: DamienFremont   File: Executor.java    License: MIT License 5 votes vote down vote up
private static DefaultHttpClient initHttpClient()
{
	DefaultHttpClient httpClient = new DefaultHttpClient();
	HttpParams params = httpClient.getParams();
	HttpConnectionParams.setConnectionTimeout( params, connectionTimeoutMillis );
	HttpConnectionParams.setSoTimeout( params, socketTimeoutMillis );
	return httpClient;
}
 
Example #20
Source Project: lucene-solr   Author: apache   File: SolrPortAwareCookieSpecFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CookieSpec newInstance(final HttpParams params) {
  if (params != null) {
    String[] patterns = null;
    final Collection<?> param = (Collection<?>) params.getParameter(
        CookieSpecPNames.DATE_PATTERNS);
    if (param != null) {
      patterns = new String[param.size()];
      patterns = param.toArray(patterns);
    }
    return new PortAwareCookieSpec(patterns);
  } else {
    return new PortAwareCookieSpec(null);
  }
}
 
Example #21
Source Project: Android-Basics-Codes   Author: DuGuQiuBai   File: AsyncHttpClient.java    License: Artistic License 2.0 5 votes vote down vote up
/**
 * Sets the Proxy by it's hostname,port,username and password
 *
 * @param hostname the hostname (IP or DNS name)
 * @param port     the port number. -1 indicates the scheme default port.
 * @param username the username
 * @param password the password
 */
public void setProxy(String hostname, int port, String username, String password) {
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(hostname, port),
            new UsernamePasswordCredentials(username, password));
    final HttpHost proxy = new HttpHost(hostname, port);
    final HttpParams httpParams = this.httpClient.getParams();
    httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
 
Example #22
Source Project: Kingdee-K3Cloud-Web-Api   Author: cashlifei   File: ApiRequest.java    License: GNU General Public License v3.0 5 votes vote down vote up
private HttpClient getHttpClient() {
    if (this._httpClient == null) {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");

        HttpConnectionParams.setConnectionTimeout(params, 300000);

        HttpConnectionParams.setSoTimeout(params, 300000);

        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http",
                PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https",
                SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
                params, schReg);
        this._httpClient = new DefaultHttpClient(conMgr, params);

        if (this._cookieStore != null) {
            DefaultHttpClient dhttpclient = (DefaultHttpClient) this._httpClient;
            dhttpclient.setCookieStore(this._cookieStore);
        }
    }
    return this._httpClient;
}
 
Example #23
Source Project: android-download-manager   Author: bytebeats   File: AndroidHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
	this.delegate = new DefaultHttpClient(ccm, params) {
		@Override
		protected BasicHttpProcessor createHttpProcessor() {
			// Add interceptor to prevent making requests from main thread.
			BasicHttpProcessor processor = super.createHttpProcessor();
			processor.addRequestInterceptor(sThreadCheckInterceptor);
			processor.addRequestInterceptor(new CurlLogger());

			return processor;
		}

		@Override
		protected HttpContext createHttpContext() {
			// Same as DefaultHttpClient.createHttpContext() minus the
			// cookie store.
			HttpContext context = new BasicHttpContext();
			context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
					getAuthSchemes());
			context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
					getCookieSpecs());
			context.setAttribute(ClientContext.CREDS_PROVIDER,
					getCredentialsProvider());
			return context;
		}
	};
}
 
Example #24
Source Project: docker-java-api   Author: amihaiemil   File: UnixHttpClientTestCase.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * UnixHttpClient returns its HttpParams.
 */
@Test
public void getsHttpParams() {
    final HttpParams params = Mockito.mock(HttpParams.class);
    final HttpClient decorated = Mockito.mock(HttpClient.class);
    Mockito.when(decorated.getParams()).thenReturn(params);

    final HttpClient unix = new UnixHttpClient(() -> decorated);
    MatcherAssert.assertThat(unix.getParams(), Matchers.is(params));
    Mockito.verify(
        decorated, Mockito.times(1)
    ).getParams();
}
 
Example #25
Source Project: neembuu-uploader   Author: Neembuu-Uploader   File: FileDenUploaderPlugin.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void loginFileDen() throws Exception {


        cookies = new StringBuilder();
        HttpParams params = new BasicHttpParams();
        params.setParameter(
                "http.useragent",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
        DefaultHttpClient httpclient = new DefaultHttpClient(params);

        System.out.println("Trying to log in to fileden.com");
        HttpPost httppost = new HttpPost("http://www.fileden.com/account.php?action=login");
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("action", "login"));
        formparams.add(new BasicNameValuePair("task", "login"));
        formparams.add(new BasicNameValuePair("username", "007007dinesh"));
        formparams.add(new BasicNameValuePair("password", ""));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(entity);
        HttpResponse httpresponse = httpclient.execute(httppost);
        System.out.println("Getting cookies........");
        //System.out.println(EntityUtils.toString(httpresponse.getEntity()));
        Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator();
        Cookie escookie = null;
        while (it.hasNext()) {
            escookie = it.next();
            cookies.append(escookie.getName()).append("=").append(escookie.getValue()).append(";");
        }
        if (cookies.toString().contains("uploader_username")) {
            login = true;
        }
        if (login) {
            System.out.println("FileDen Login success :)");
            System.out.println(cookies);
        } else {
            System.out.println("FileDen Login failed :(");
        }


    }
 
Example #26
Source Project: travelguide   Author: mapsme   File: AndroidHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
        @Override
        protected BasicHttpProcessor createHttpProcessor() {
            // Add interceptor to prevent making requests from main thread.
            BasicHttpProcessor processor = super.createHttpProcessor();
            processor.addRequestInterceptor(sThreadCheckInterceptor);
            processor.addRequestInterceptor(new CurlLogger());

            return processor;
        }

        @Override
        protected HttpContext createHttpContext() {
            // Same as DefaultHttpClient.createHttpContext() minus the
            // cookie store.
            HttpContext context = new BasicHttpContext();
            context.setAttribute(
                    ClientContext.AUTHSCHEME_REGISTRY,
                    getAuthSchemes());
            context.setAttribute(
                    ClientContext.COOKIESPEC_REGISTRY,
                    getCookieSpecs());
            context.setAttribute(
                    ClientContext.CREDS_PROVIDER,
                    getCredentialsProvider());
            return context;
        }
    };
}
 
Example #27
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: HttpUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute Http request and response code
 * @param request - HTTP Request
 * @param expectedCode - expected response code
 * @return - response in JSONObject
 */
public JSON query(HttpRequestBase request, int expectedCode) throws IOException {
    log.info("Requesting: " + request);
    addRequiredHeader(request);

    HttpParams requestParams = request.getParams();
    requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT * 1000);
    requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT * 1000);

    synchronized (httpClient) {
        String response;
        try {
            HttpResponse result = httpClient.execute(request);

            int statusCode = result.getStatusLine().getStatusCode();

            response = getResponseEntity(result);

            if (statusCode != expectedCode) {

                notifier.notifyAbout("Response with code " + statusCode + ": " + extractErrorMessage(response));
                throw new IOException("API responded with wrong status code: " + statusCode);
            } else {
                log.debug("Response: " + response);
            }
        } finally {
            request.abort();
        }

        if (response == null || response.isEmpty()) {
            return JSONNull.getInstance();
        } else {
            return JSONSerializer.toJSON(response, new JsonConfig());
        }
    }
}
 
Example #28
Source Project: MiBandDecompiled   Author: vishnudevk   File: AsyncHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
public void setEnableRedirects(boolean flag, boolean flag1, boolean flag2)
{
    HttpParams httpparams = c.getParams();
    boolean flag3;
    if (!flag1)
    {
        flag3 = true;
    } else
    {
        flag3 = false;
    }
    httpparams.setBooleanParameter("http.protocol.reject-relative-redirect", flag3);
    c.getParams().setBooleanParameter("http.protocol.allow-circular-redirects", flag2);
    c.setRedirectHandler(new w(flag));
}
 
Example #29
Source Project: BigApp_Discuz_Android   Author: BigAppOS   File: HttpUtils.java    License: Apache License 2.0 5 votes vote down vote up
public HttpUtils configTimeout(int timeout) {
    final HttpParams httpParams = this.httpClient.getParams();
    ConnManagerParams.setTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    return this;
}
 
Example #30
Source Project: letv   Author: JackChan1999   File: HttpEngine.java    License: Apache License 2.0 5 votes vote down vote up
public DefaultHttpClient createHttpClient() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme(IDataSource.SCHEME_HTTP_TAG, PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme(IDataSource.SCHEME_HTTPS_TAG, SSLSocketFactory.getSocketFactory(), 443));
    HttpParams params = createHttpParams();
    return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
}