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

The following examples show how to use org.apache.http.impl.client.AbstractHttpClient. 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: Http4Util.java    From httpsig-java with 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 #2
Source File: RestAdapter.java    From io with 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 #3
Source File: HttpClientFactoryImpl.java    From swift-explorer with 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 File: HttpHelper.java    From miappstore with 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 #5
Source File: AsyncHttpRequest.java    From sealtalk-android with 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 #6
Source File: HttpUtils.java    From jmeter-bzm-plugins with 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 File: HttpUtil.java    From Leo with 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 #8
Source File: ReadWebpage.java    From codeexamples-android with 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 #9
Source File: AsyncHttpRequest.java    From Roid-Library with 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 #10
Source File: LayerHttpServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #11
Source File: HttpHandler.java    From android-open-project-demo with 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 #12
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 #13
Source File: DispatchService.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #14
Source File: HttpsDispatcher.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #15
Source File: AsyncHttpRequest.java    From MiBandDecompiled with 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 #16
Source File: HttpHelper.java    From NetEasyNews with 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 #17
Source File: UsingWithRestAssuredTest.java    From curl-logger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public HttpClient createHttpClient() {
  AbstractHttpClient client = new DefaultHttpClient();
  client.addRequestInterceptor(new CurlTestingInterceptor(curlConsumer));
  return client;
}
 
Example #18
Source File: AsyncHttpRequest.java    From letv with 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 #19
Source File: RegisterMobileFragment.java    From letv with 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 #20
Source File: HttpSolrClientFactory.java    From dubbox with 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 #21
Source File: HttpHandler.java    From BigApp_Discuz_Android with 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 #22
Source File: CurlLoggingRestAssuredConfigFactory.java    From curl-logger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public HttpClient createHttpClient() {
  final AbstractHttpClient client = (AbstractHttpClient) wrappedFactory.createHttpClient();
  client.addRequestInterceptor(curlLoggingInterceptor);
  return client;
}
 
Example #23
Source File: CurlLoggingRestAssuredConfigFactoryTest.java    From curl-logger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #24
Source File: CurlLoggingRestAssuredConfigFactoryTest.java    From curl-logger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #25
Source File: SyncHttpHandler.java    From android-open-project-demo with 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;
}
 
Example #26
Source File: ApiRequest.java    From Kingdee-K3Cloud-Web-Api with GNU General Public License v3.0 4 votes vote down vote up
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 #27
Source File: HttpUtils.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
public AbstractHttpClient getHttpClient() {
    return httpClient;
}
 
Example #28
Source File: AsyncHttpRequest.java    From Libraries-for-Android-Developers with MIT License 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 File: OAuth1.java    From hbc with Apache License 2.0 4 votes vote down vote up
@Override
public void setupConnection(AbstractHttpClient client) {}
 
Example #30
Source File: BasicAuth.java    From hbc with Apache License 2.0 4 votes vote down vote up
public void setupConnection(AbstractHttpClient client) {
  client.getCredentialsProvider().setCredentials(
          AuthScope.ANY,
          new UsernamePasswordCredentials(username, password)
  );
}