下面列出了怎么用org.apache.http.impl.client.AbstractHttpClient的API类实例代码及写法,或者点击链接到github查看源代码。
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 + "-");
}
}
}
/** 执行网络访问 */
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;
}
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()));
}
/**
* 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));
}
}
}
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);
}
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;
}
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;
}
}
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;
}
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));
}
}
}
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;
}
@SuppressWarnings("deprecation")
@Override
public HttpClient createHttpClient() {
AbstractHttpClient client = new DefaultHttpClient();
client.addRequestInterceptor(new CurlTestingInterceptor(curlConsumer));
return client;
}
/**
* 执行网络访问
*/
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);
}
}
}
}
public AsyncHttpRequest(AbstractHttpClient abstracthttpclient, HttpContext httpcontext, HttpUriRequest httpurirequest, ResponseHandlerInterface responsehandlerinterface)
{
f = false;
g = false;
h = false;
a = abstracthttpclient;
b = httpcontext;
c = httpurirequest;
d = responsehandlerinterface;
}
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;
}
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);
}
@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);
}
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());
}
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;
}
}
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;
}
}
/**
* 获取返回结果中的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();
}
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();
}
}
}
public AbstractHttpClient getHttpClient() {
return httpClient;
}
private boolean assertHttpClientInstance(HttpClient httpClient) {
Assert.isInstanceOf(AbstractHttpClient.class, httpClient,
"HttpClient has to be derivate of AbstractHttpClient in order to allow authentication.");
return true;
}
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, ResponseHandlerInterface responseHandler) {
this.client = client;
this.context = context;
this.request = request;
this.responseHandler = responseHandler;
}
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");
}
public SyncHttpHandler(AbstractHttpClient client, HttpContext context, String charset) {
this.client = client;
this.context = context;
this.charset = charset;
}