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 File: ImmersionHttpClient.java    From letv with 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 #2
Source File: GetClient.java    From javabase with 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 #3
Source File: ApiProxyServlet.java    From onboard with 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 File: NetWorkTool.java    From FoodOrdering with 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 File: HttpLoadTestClient.java    From carbon-apimgt with 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 File: BasicClient.java    From hbc with 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 #7
Source File: HttpContinueAcceptingHandlerTestCase.java    From quarkus-http with 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 #8
Source File: CheckUser.java    From neembuu-uploader with 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 File: MySSLSocketFactory.java    From Libraries-for-Android-Developers with 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 #10
Source File: EMQClientFactory.java    From galaxy-sdk-java with 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 File: HttpClientStack.java    From android-project-wo2b with 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 File: FileDenUploaderPlugin.java    From neembuu-uploader with 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 #13
Source File: HttpUtils.java    From LitePlayer with 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 #14
Source File: AsyncHttpClient.java    From Mobike with Apache 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 #15
Source File: Download.java    From LitePlayer with Apache License 2.0 5 votes vote down vote up
/**
	 * 设置http参数 不能设置soTimeout
	 * @return HttpParams http参数
	 */
	private static HttpParams getHttpParams() {
		HttpParams params = new BasicHttpParams();

		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		HttpProtocolParams.setUseExpectContinue(params, true);
		HttpProtocolParams.setUserAgent(params, UA);
//		ConnManagerParams.setTimeout(params, 10000);
//		HttpConnectionParams.setConnectionTimeout(params, 10000);
		
		return params;
	}
 
Example #16
Source File: ApacheHttpTransport.java    From google-http-java-client with 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 #17
Source File: HttpClientStack.java    From device-database with 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 #18
Source File: ApiRequest.java    From Kingdee-K3Cloud-Web-Api with 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 #19
Source File: RestService.java    From kylin with Apache License 2.0 5 votes vote down vote up
private HttpClient getHttpClient(int connectionTimeout, int readTimeout) {
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, readTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);

    return new DefaultHttpClient(httpParams);
}
 
Example #20
Source File: AndroidHttpClient.java    From android-download-manager with 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 #21
Source File: HttpClientStack.java    From SimplifyReader with 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 #22
Source File: UnixHttpClientTestCase.java    From docker-java-api with 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 #23
Source File: FetchThumbnailTask.java    From iZhihu with GNU General Public License v2.0 5 votes vote down vote up
public FetchThumbnailTask(Context context, ThumbnailsDatabase database, List<String> urls, BaseTasks.Callback callback) {
    super(context, callback);

    this.mDatabase = database;
    this.httpClient = new DefaultHttpClient();
    this.urls = urls;
    this.context = context;

    HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_SECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SECONDS);
    HttpProtocolParams.setUserAgent(httpParams, USER_AGENT_STRING);

    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
 
Example #24
Source File: AndroidHttpClient.java    From travelguide with 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 #25
Source File: HttpClientIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPost post = new HttpPost(webServer.getCallHttpUrl());
        post.addHeader("Content-Type", "application/json;charset=UTF-8");

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        httpClient.execute(post, responseHandler);
    } catch (Exception ignored) {
    } finally {
        if (null != httpClient && null != httpClient.getConnectionManager()) {
            httpClient.getConnectionManager().shutdown();
        }
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Class<?> connectorClass;
    
    try {
        connectorClass = Class.forName("org.apache.http.impl.conn.ManagedClientConnectionImpl");
    } catch (ClassNotFoundException e) {
        connectorClass = Class.forName("org.apache.http.impl.conn.AbstractPooledConnAdapter");
    }
    
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", AbstractHttpClient.class.getMethod("execute", HttpUriRequest.class, ResponseHandler.class)));
    final String hostname = webServer.getHostAndPort();
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", connectorClass.getMethod("open", HttpRoute.class, HttpContext.class, HttpParams.class), annotation("http.internal.display", hostname)));
    verifier.verifyTrace(event("HTTP_CLIENT_4", HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class, HttpContext.class), null, null, hostname, annotation("http.url", "/"), annotation("http.status.code", 200), annotation("http.io", anyAnnotationValue())));
    verifier.verifyTraceCount(0);
}
 
Example #26
Source File: HttpUtils.java    From jmeter-bzm-plugins with 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 #27
Source File: AsyncHttpClient.java    From MiBandDecompiled with 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 #28
Source File: HttpUtils.java    From BigApp_Discuz_Android with 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 #29
Source File: CustomConnectionsHttpClientFactory.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpMessageParser<HttpResponse> createResponseParser(
        final SessionInputBuffer buffer,
        final HttpResponseFactory responseFactory,
        final HttpParams params) {

  return new DefaultHttpResponseParser(
          buffer,
          new MyLineParser(),
          responseFactory,
          params);
}
 
Example #30
Source File: HttpEngine.java    From letv with 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);
}