类org.apache.http.impl.client.AbstractHttpClient源码实例Demo

下面列出了怎么用org.apache.http.impl.client.AbstractHttpClient的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: sealtalk-android   文件: AsyncHttpRequest.java
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 + "-");
}
     }
 }
 
源代码2 项目: miappstore   文件: HttpHelper.java
/** 执行网络访问 */
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;
}
 
源代码3 项目: swift-explorer   文件: HttpClientFactoryImpl.java
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()));  
}
 
源代码4 项目: io   文件: RestAdapter.java
/**
 * 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));
        }
    }
}
 
源代码5 项目: httpsig-java   文件: Http4Util.java
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);
}
 
源代码6 项目: jmeter-bzm-plugins   文件: HttpUtils.java
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;
}
 
源代码7 项目: letv   文件: AsyncHttpRequest.java
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;
    }
}
 
源代码8 项目: letv   文件: RegisterMobileFragment.java
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;
}
 
源代码9 项目: dubbox   文件: HttpSolrClientFactory.java
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));
		}
	}
}
 
源代码10 项目: BigApp_Discuz_Android   文件: HttpHandler.java
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);
}
 
@Override
@SuppressWarnings("deprecation")
public HttpClient createHttpClient() {
  final AbstractHttpClient client = (AbstractHttpClient) wrappedFactory.createHttpClient();
  client.addRequestInterceptor(curlLoggingInterceptor);
  return client;
}
 
@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"));

}
 
@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;
}
 
源代码14 项目: curl-logger   文件: UsingWithRestAssuredTest.java
@SuppressWarnings("deprecation")
@Override
public HttpClient createHttpClient() {
  AbstractHttpClient client = new DefaultHttpClient();
  client.addRequestInterceptor(new CurlTestingInterceptor(curlConsumer));
  return client;
}
 
源代码15 项目: NetEasyNews   文件: HttpHelper.java
/**
     * 执行网络访问
     */
    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);
                }
            }
        }
    }
 
源代码16 项目: MiBandDecompiled   文件: AsyncHttpRequest.java
public AsyncHttpRequest(AbstractHttpClient abstracthttpclient, HttpContext httpcontext, HttpUriRequest httpurirequest, ResponseHandlerInterface responsehandlerinterface)
{
    f = false;
    g = false;
    h = false;
    a = abstracthttpclient;
    b = httpcontext;
    c = httpurirequest;
    d = responsehandlerinterface;
}
 
源代码17 项目: sana.mobile   文件: HttpsDispatcher.java
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;
    }
 
源代码18 项目: sana.mobile   文件: DispatchService.java
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);
    }
 
源代码19 项目: pinpoint   文件: HttpClientIT.java
@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);
}
 
源代码20 项目: android-open-project-demo   文件: HttpHandler.java
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);
}
 
@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());
}
 
源代码22 项目: Roid-Library   文件: AsyncHttpRequest.java
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;
    }
}
 
源代码23 项目: codeexamples-android   文件: ReadWebpage.java
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;
	}
}
 
源代码24 项目: Leo   文件: HttpUtil.java
/**
 * 获取返回结果中的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();
}
 
源代码25 项目: Kingdee-K3Cloud-Web-Api   文件: ApiRequest.java
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();
        }
    }
}
 
源代码26 项目: jmeter-bzm-plugins   文件: HttpUtils.java
public AbstractHttpClient getHttpClient() {
    return httpClient;
}
 
源代码27 项目: dubbox   文件: HttpSolrClientFactory.java
private boolean assertHttpClientInstance(HttpClient httpClient) {
	Assert.isInstanceOf(AbstractHttpClient.class, httpClient,
			"HttpClient has to be derivate of AbstractHttpClient in order to allow authentication.");
	return true;
}
 
源代码28 项目: Mobike   文件: AsyncHttpRequest.java
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, ResponseHandlerInterface responseHandler) {
    this.client = client;
    this.context = context;
    this.request = request;
    this.responseHandler = responseHandler;
}
 
源代码29 项目: AndroidWear-OpenWear   文件: AsyncHttpRequest.java
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");
}
 
源代码30 项目: BigApp_Discuz_Android   文件: SyncHttpHandler.java
public SyncHttpHandler(AbstractHttpClient client, HttpContext context, String charset) {
    this.client = client;
    this.context = context;
    this.charset = charset;
}
 
 同包方法