Java Code Examples for org.apache.http.impl.client.AbstractHttpClient

The following examples show how to use org.apache.http.impl.client.AbstractHttpClient. These examples are extracted from open source projects. 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: sealtalk-android   Source File: AsyncHttpRequest.java    License: MIT License 6 votes vote down vote up
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, ResponseHandlerInterface responseHandler) {
     this.client = client;
     this.context = context;
     this.request = request;
     this.responseHandler = responseHandler;
     
     //断点续传处理
     if(this.responseHandler instanceof BreakpointHttpResponseHandler){
     	BreakpointHttpResponseHandler breakpointHandler = (BreakpointHttpResponseHandler)this.responseHandler;
     	File tempFile = breakpointHandler.getTempFile();
     	if (tempFile.exists()) {
	long previousFileSize = tempFile.length();
	Log.e(tag, "previousFileSized: " + previousFileSize);
	this.request.setHeader("RANGE", "bytes=" + previousFileSize + "-");
}
     }
 }
 
Example 2
Source Project: miappstore   Source File: HttpHelper.java    License: Apache License 2.0 6 votes vote down vote up
/** 执行网络访问 */
private static HttpResult execute(String url, HttpRequestBase requestBase) {
	boolean isHttps = url.startsWith("https://");//判断是否需要采用https
	AbstractHttpClient httpClient = HttpClientFactory.create(isHttps);
	HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
	HttpRequestRetryHandler retryHandler = httpClient.getHttpRequestRetryHandler();//获取重试机制
	int retryCount = 0;
	boolean retry = true;
	while (retry) {
		try {
			HttpResponse response = httpClient.execute(requestBase, httpContext);//访问网络
			if (response != null) {
				return new HttpResult(response, httpClient, requestBase);
			}
		} catch (Exception e) {
			IOException ioException = new IOException(e.getMessage());
			retry = retryHandler.retryRequest(ioException, ++retryCount, httpContext);//把错误异常交给重试机制,以判断是否需要采取从事
		}
	}
	return null;
}
 
Example 3
Source Project: swift-explorer   Source File: HttpClientFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void setProxySettings (org.apache.http.client.HttpClient client, HasProxySettings proxySettings, String prot)
{
	if (client == null)
		return ;
       if (proxySettings == null || !proxySettings.isActive())
       	return ;
       if (prot == null || prot.isEmpty())
       	return ;
                   
   	org.apache.http.HttpHost proxy = new org.apache.http.HttpHost(proxySettings.getHost(), proxySettings.getPort(), prot) ;
   	client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy) ;
   	
   	CredentialsProvider credProvider = ((AbstractHttpClient) client).getCredentialsProvider();
   	credProvider.setCredentials(
   			new AuthScope(proxySettings.getHost(), proxySettings.getPort()), 
   			new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword()));  
}
 
Example 4
Source Project: io   Source File: RestAdapter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This is the parameterized constructor to initialize various fields.
 * @param as Accessor
 */
public RestAdapter(Accessor as) {
    this.accessor = as;
    DaoConfig config = accessor.getDaoConfig();
    httpClient = config.getHttpClient();
    if (httpClient == null) {
        httpClient = HttpClientFactory.create(DcContext.getPlatform(), config.getConnectionTimeout());
    }
    String proxyHost = config.getProxyHostname();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // ID/Passが共にnullでなければ認証Proxyをセット
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        if (httpClient instanceof AbstractHttpClient && proxyUsername != null && proxyPassword != null) {
            ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }
}
 
Example 5
Source Project: httpsig-java   Source File: Http4Util.java    License: The Unlicense 6 votes vote down vote up
public static void enableAuth(final AbstractHttpClient client, final Keychain keychain, final KeyId keyId) {
    if (client == null) {
        throw new NullPointerException("client");
    }

    if (keychain == null) {
        throw new NullPointerException("keychain");
    }

    client.getAuthSchemes().register(Constants.SCHEME, new AuthSchemeFactory() {
        public AuthScheme newInstance(HttpParams params) {
            return new Http4SignatureAuthScheme();
        }
    });

    Signer signer = new Signer(keychain, keyId);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, new SignerCredentials(signer));
    client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
                                    Arrays.asList(Constants.SCHEME));

    HttpClientParams.setAuthenticating(client.getParams(), true);
}
 
Example 6
Source Project: jmeter-bzm-plugins   Source File: HttpUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static AbstractHttpClient createHTTPClient() {
    AbstractHttpClient client = new DefaultHttpClient();
    String proxyHost = System.getProperty("https.proxyHost", "");
    if (!proxyHost.isEmpty()) {
        int proxyPort = Integer.parseInt(System.getProperty("https.proxyPort", "-1"));
        log.info("Using proxy " + proxyHost + ":" + proxyPort);
        HttpParams params = client.getParams();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        String proxyUser = System.getProperty(JMeter.HTTP_PROXY_USER, JMeterUtils.getProperty(JMeter.HTTP_PROXY_USER));
        if (proxyUser != null) {
            log.info("Using authenticated proxy with username: " + proxyUser);
            String proxyPass = System.getProperty(JMeter.HTTP_PROXY_PASS, JMeterUtils.getProperty(JMeter.HTTP_PROXY_PASS));

            String localHost;
            try {
                localHost = InetAddress.getLocalHost().getCanonicalHostName();
            } catch (Throwable e) {
                log.error("Failed to get local host name, defaulting to 'localhost'", e);
                localHost = "localhost";
            }

            AuthScope authscope = new AuthScope(proxyHost, proxyPort);
            String proxyDomain = JMeterUtils.getPropDefault("http.proxyDomain", "");
            NTCredentials credentials = new NTCredentials(proxyUser, proxyPass, localHost, proxyDomain);
            client.getCredentialsProvider().setCredentials(authscope, credentials);
        }
    }
    return client;
}
 
Example 7
Source Project: letv   Source File: AsyncHttpRequest.java    License: Apache License 2.0 5 votes vote down vote up
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, AsyncHttpResponseHandler responseHandler) {
    this.client = client;
    this.context = context;
    this.request = request;
    this.responseHandler = responseHandler;
    if (responseHandler instanceof BinaryHttpResponseHandler) {
        this.isBinaryRequest = true;
    }
}
 
Example 8
Source Project: letv   Source File: RegisterMobileFragment.java    License: Apache License 2.0 5 votes vote down vote up
private String getCaptchaId(HttpClient httpClient) {
    List<Cookie> cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
    String captchaId = null;
    for (int i = 0; i < cookies.size(); i++) {
        Cookie cookie = (Cookie) cookies.get(i);
        String cookieName = cookie.getName();
        if (!TextUtils.isEmpty(cookieName) && cookieName.equals("captchaId")) {
            captchaId = cookie.getValue();
        }
    }
    return captchaId;
}
 
Example 9
Source Project: dubbox   Source File: HttpSolrClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
private void appendAuthentication(Credentials credentials, String authPolicy, SolrClient solrClient) {
	if (isHttpSolrClient(solrClient)) {
		HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient;

		if (credentials != null && StringUtils.isNotBlank(authPolicy)
				&& assertHttpClientInstance(httpSolrClient.getHttpClient())) {
			AbstractHttpClient httpClient = (AbstractHttpClient) httpSolrClient.getHttpClient();
			httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
			httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(authPolicy));
		}
	}
}
 
Example 10
Source Project: BigApp_Discuz_Android   Source File: HttpHandler.java    License: Apache License 2.0 5 votes vote down vote up
public HttpHandler(AbstractHttpClient client, HttpContext context, String charset, RequestCallBack<T> callback) {
    this.client = client;
    this.context = context;
    this.callback = callback;
    this.charset = charset;
    this.client.setRedirectHandler(notUseApacheRedirectHandler);
}
 
Example 11
@Override
@SuppressWarnings("deprecation")
public HttpClient createHttpClient() {
  final AbstractHttpClient client = (AbstractHttpClient) wrappedFactory.createHttpClient();
  client.addRequestInterceptor(curlLoggingInterceptor);
  return client;
}
 
Example 12
@Test
public void shouldIncludeCurlInterceptorWhenUpdatingExistingConfig() {

  HttpClientConfig httpClientConfig = HttpClientConfig.httpClientConfig()
      .setParam("TestParam", "TestValue")
      .httpClientFactory(
          new HttpClientConfig.HttpClientFactory() {
            @Override
            public HttpClient createHttpClient() {
              DefaultHttpClient client = new DefaultHttpClient();
              client.addRequestInterceptor(new MyRequestInerceptor());
              return client;
            }
          }
      );
  final RestAssuredConfig config = RestAssuredConfig.config()
      .httpClient(httpClientConfig);

  RestAssuredConfig updatedConfig = CurlLoggingRestAssuredConfigFactory.updateConfig(config, Options.builder().build());

  // original configuration has not been modified
  assertThat(updatedConfig, not(equalTo(config)));
  AbstractHttpClient clientConfig = (AbstractHttpClient) config.getHttpClientConfig().httpClientInstance();
  assertThat(clientConfig, not(new ContainsRequestInterceptor(CurlLoggingInterceptor.class)));
  assertThat(clientConfig, new ContainsRequestInterceptor(MyRequestInerceptor.class));
  assertThat(updatedConfig.getHttpClientConfig().params().get("TestParam"), equalTo("TestValue"));

  // curl logging interceptor is included
  AbstractHttpClient updateClientConfig = (AbstractHttpClient) updatedConfig.getHttpClientConfig().httpClientInstance();
  assertThat(updateClientConfig, new ContainsRequestInterceptor(CurlLoggingInterceptor.class));

  // original interceptors are preserved in new configuration
  assertThat(updateClientConfig, new ContainsRequestInterceptor(MyRequestInerceptor.class));
  // original parameters are preserved in new configuration
  assertThat(updatedConfig.getHttpClientConfig().params().get("TestParam"), equalTo("TestValue"));

}
 
Example 13
@Override
protected boolean matchesSafely(AbstractHttpClient client, Description mismatchDescription) {
  for (int i = 0; i < client.getRequestInterceptorCount(); i++) {
    if (expectedRequestedInterceptor.isInstance(client.getRequestInterceptor(i))) {
      return true;
    }
  }
  return false;
}
 
Example 14
@SuppressWarnings("deprecation")
@Override
public HttpClient createHttpClient() {
  AbstractHttpClient client = new DefaultHttpClient();
  client.addRequestInterceptor(new CurlTestingInterceptor(curlConsumer));
  return client;
}
 
Example 15
Source Project: NetEasyNews   Source File: HttpHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
     * 执行网络访问
     */
    private static void execute(String url, HttpRequestBase requestBase, HttpCallbackListener httpCallbackListener) {
        boolean isHttps = url.startsWith("https://");//判断是否需要采用https
        AbstractHttpClient httpClient = HttpClientFactory.create(isHttps);
        HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
        HttpRequestRetryHandler retryHandler = httpClient.getHttpRequestRetryHandler();//获取重试机制
        int retryCount = 0;
        boolean retry = true;
        while (retry) {
            try {
                HttpResponse response = httpClient.execute(requestBase, httpContext);//访问网络
                int stateCode  = response.getStatusLine().getStatusCode();
//                LogUtils.e(TAG, "http状态码:" + stateCode);
                if (response != null) {
                    if (stateCode == HttpURLConnection.HTTP_OK){
                        HttpResult httpResult = new HttpResult(response, httpClient, requestBase);
                        String result = httpResult.getString();
                        if (!TextUtils.isEmpty(result)){
                            httpCallbackListener.onSuccess(result);
                            return;
                        } else {
                            throw new RuntimeException("数据为空");
                        }
                    } else {
                        throw new RuntimeException(HttpRequestCode.ReturnCode(stateCode));
                    }
                }
            } catch (Exception e) {
                IOException ioException = new IOException(e.getMessage());
                retry = retryHandler.retryRequest(ioException, ++retryCount, httpContext);//把错误异常交给重试机制,以判断是否需要采取从事
                LogUtils.e(TAG, "重复次数:" + retryCount + "   :"+ e);
                if (!retry){
                    httpCallbackListener.onError(e);
                }
            }
        }
    }
 
Example 16
Source Project: MiBandDecompiled   Source File: AsyncHttpRequest.java    License: Apache License 2.0 5 votes vote down vote up
public AsyncHttpRequest(AbstractHttpClient abstracthttpclient, HttpContext httpcontext, HttpUriRequest httpurirequest, ResponseHandlerInterface responsehandlerinterface)
{
    f = false;
    g = false;
    h = false;
    a = abstracthttpclient;
    b = httpcontext;
    c = httpurirequest;
    d = responsehandlerinterface;
}
 
Example 17
public static HttpsDispatcher getInstance(String uri, Credentials credentials) {

        HttpsDispatcher dispatcher = new HttpsDispatcher(new HttpHost(uri),
                new BasicHttpContext());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope authScope = new AuthScope(dispatcher.host.getHostName(), dispatcher.host.getPort());
        credsProvider.setCredentials(authScope, credentials);
        ((AbstractHttpClient) dispatcher.client).getCredentialsProvider().setCredentials(
                authScope, credentials);
        return dispatcher;
    }
 
Example 18
protected void build() throws URISyntaxException {

        URI uri = MDSInterface2.getRoot(this);
        mHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope authScope = new AuthScope(mHost.getHostName(), mHost.getPort());
        Credentials creds = new UsernamePasswordCredentials("username", "password");
        credsProvider.setCredentials(authScope, creds);

        mClient = new DefaultHttpClient();
        ((AbstractHttpClient) mClient).getCredentialsProvider().setCredentials(
                authScope, creds);
    }
 
Example 19
Source Project: pinpoint   Source File: HttpClientIT.java    License: 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 20
Source Project: android-open-project-demo   Source File: HttpHandler.java    License: Apache License 2.0 5 votes vote down vote up
public HttpHandler(AbstractHttpClient client, HttpContext context, String charset, RequestCallBack<T> callback) {
    this.client = client;
    this.context = context;
    this.callback = callback;
    this.charset = charset;
    this.client.setRedirectHandler(notUseApacheRedirectHandler);
}
 
Example 21
@Override
public void setClient(AbstractHttpClient client) {
	this.client = client;
	// add an interceptor that picks up the autowired interceptors, remove first to avoid doubles
	client.removeRequestInterceptorByClass(CompositeInterceptor.class);
	client.addRequestInterceptor(new CompositeInterceptor());
}
 
Example 22
Source Project: Roid-Library   Source File: AsyncHttpRequest.java    License: Apache License 2.0 5 votes vote down vote up
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request,
        AsyncHttpResponseHandler responseHandler) {
    this.client = client;
    this.context = context;
    this.request = request;
    this.responseHandler = responseHandler;
    if (responseHandler instanceof BinaryHttpResponseHandler) {
        this.isBinaryRequest = true;
    }
}
 
Example 23
Source Project: codeexamples-android   Source File: ReadWebpage.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void myClickHandler(View view) {
	switch (view.getId()) {
	case R.id.ReadWebPage:
		try {
			textView.setText("");

			// Cast to AbstractHttpClient to have access to
			// setHttpRequestRetryHandler
			AbstractHttpClient client = (AbstractHttpClient) new DefaultHttpClient();

			HttpGet request = new HttpGet(urlText.getText().toString());
			HttpResponse response = client.execute(request);
			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				textView.append(line);
			}
		}

		catch (Exception e) {
			System.out.println("Nay, did not work");
			textView.setText(e.getMessage());
		}
		break;
	}
}
 
Example 24
Source Project: Leo   Source File: HttpUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取返回结果中的cookies信息
 * @return
 */
private String getCookies(){
	StringBuilder sb = new StringBuilder();
       List<Cookie> cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
       for(Cookie cookie: cookies)
           sb.append(cookie.getName() + "=" + cookie.getValue() + ";");
       return sb.toString();
}
 
Example 25
public void doPost() {
    HttpPost httpPost = getHttpPost();
    try {
        if (httpPost == null) {
            return;
        }

        httpPost.setEntity(getServiceParameters().toEncodeFormEntity());
        this._response = getHttpClient().execute(httpPost);

        if (this._response.getStatusLine().getStatusCode() == 200) {
            HttpEntity respEntity = this._response.getEntity();

            if (this._currentsessionid == "") {
                CookieStore mCookieStore = ((AbstractHttpClient) getHttpClient())
                        .getCookieStore();
                List cookies = mCookieStore.getCookies();
                if (cookies.size() > 0) {
                    this._cookieStore = mCookieStore;
                }
                for (int i = 0; i < cookies.size(); i++) {
                    if (_aspnetsessionkey.equals(((Cookie) cookies.get(i)).getName())) {
                        this._aspnetsessionid = ((Cookie) cookies.get(i)).getValue();
                    }

                    if (_sessionkey.equals(((Cookie) cookies.get(i)).getName())) {
                        this._currentsessionid = ((Cookie) cookies.get(i)).getValue();
                    }
                }

            }

            this._responseStream = respEntity.getContent();
            this._responseString = streamToString(this._responseStream);

            if (this._isAsynchronous.booleanValue()) {
                this._listener.onRequsetSuccess(this);
            }
        }
    } catch (Exception e) {
        if (this._isAsynchronous.booleanValue()) {
            this._listener.onRequsetError(this, e);
        }
    } finally {
        if (httpPost != null) {
            httpPost.abort();
        }
    }
}
 
Example 26
Source Project: jmeter-bzm-plugins   Source File: HttpUtils.java    License: Apache License 2.0 4 votes vote down vote up
public AbstractHttpClient getHttpClient() {
    return httpClient;
}
 
Example 27
Source Project: dubbox   Source File: HttpSolrClientFactory.java    License: Apache License 2.0 4 votes vote down vote up
private boolean assertHttpClientInstance(HttpClient httpClient) {
	Assert.isInstanceOf(AbstractHttpClient.class, httpClient,
			"HttpClient has to be derivate of AbstractHttpClient in order to allow authentication.");
	return true;
}
 
Example 28
Source Project: Mobike   Source File: AsyncHttpRequest.java    License: Apache License 2.0 4 votes vote down vote up
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, ResponseHandlerInterface responseHandler) {
    this.client = client;
    this.context = context;
    this.request = request;
    this.responseHandler = responseHandler;
}
 
Example 29
Source Project: AndroidWear-OpenWear   Source File: AsyncHttpRequest.java    License: MIT License 4 votes vote down vote up
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, ResponseHandlerInterface responseHandler) {
    this.client = Utils.notNull(client, "client");
    this.context = Utils.notNull(context, "context");
    this.request = Utils.notNull(request, "request");
    this.responseHandler = Utils.notNull(responseHandler, "responseHandler");
}
 
Example 30
Source Project: BigApp_Discuz_Android   Source File: SyncHttpHandler.java    License: Apache License 2.0 4 votes vote down vote up
public SyncHttpHandler(AbstractHttpClient client, HttpContext context, String charset) {
    this.client = client;
    this.context = context;
    this.charset = charset;
}