本文整理汇总了Java中org.apache.http.impl.client.AbstractHttpClient类的典型用法代码示例。如果您正苦于以下问题:Java AbstractHttpClient类的具体用法?Java AbstractHttpClient怎么用?Java AbstractHttpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AbstractHttpClient类属于org.apache.http.impl.client包,在下文中一共展示了AbstractHttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: execute
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
/** 执行网络访问 */
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;
}
示例2: createHTTPClient
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
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;
}
示例3: AsyncHttpRequest
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
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 + "-");
}
}
}
示例4: execute
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
/** 执行网络访问 */
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);//把错误异常交给重试机制,以判断是否需要采取从事
LogUtils.e(e);
}
}
return null;
}
示例5: AsyncHttpRequest
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
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 + "-");
}
}
}
示例6: setupClient
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
/**
* This method is used to capture Location headers after HttpClient redirect handling.
*/
private void setupClient(final AbstractHttpClient client) {
this.client.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
Header header = response.getFirstHeader("Location");
if (header!=null) {
String location = header.getValue();
/*
* Append the base name to the Location header
*/
if (location.startsWith("/")) {
String baseUrl = context.getAttribute(ExecutionContext.HTTP_TARGET_HOST).toString();
location = baseUrl + location;
}
context.setAttribute("Location", location);
}
}
});
}
示例7: setupCredentials
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
/**
* Configure credentials and auth scheme on client if an authorization is
* available for url
* @param client {@link HttpClient}
* @param url URL to test
* @param credentialsProvider {@link CredentialsProvider}
* @param localHost host running JMeter
*/
public void setupCredentials(HttpClient client, URL url,
CredentialsProvider credentialsProvider, String localHost) {
Authorization auth = getAuthForURL(url);
if (auth != null) {
String username = auth.getUser();
String realm = auth.getRealm();
String domain = auth.getDomain();
if (log.isDebugEnabled()){
log.debug(username + " > D="+domain+" R="+realm + " M="+auth.getMechanism());
}
if (Mechanism.KERBEROS.equals(auth.getMechanism())) {
((AbstractHttpClient) client).getAuthSchemes().register(
AuthSchemes.SPNEGO,
new FixedSPNegoSchemeFactory(isStripPort(url)));
credentialsProvider.setCredentials(new AuthScope(null, -1, null), USE_JAAS_CREDENTIALS);
} else {
credentialsProvider.setCredentials(
new AuthScope(url.getHost(), url.getPort(), realm.length()==0 ? null : realm),
new NTCredentials(username, auth.getPass(), localHost, domain));
}
}
}
示例8: setConnectionAuthorization
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
/**
* Setup credentials for url AuthScope but keeps Proxy AuthScope credentials
* @param client HttpClient
* @param url URL
* @param authManager {@link AuthManager}
* @param key key
*/
private void setConnectionAuthorization(HttpClient client, URL url, AuthManager authManager, HttpClientKey key) {
CredentialsProvider credentialsProvider =
((AbstractHttpClient) client).getCredentialsProvider();
if (authManager != null) {
if(authManager.hasAuthForURL(url)) {
authManager.setupCredentials(client, url, credentialsProvider, localHost);
} else {
credentialsProvider.clear();
}
} else {
Credentials credentials = null;
AuthScope authScope = null;
if(key.hasProxy && !StringUtils.isEmpty(key.proxyUser)) {
authScope = new AuthScope(key.proxyHost, key.proxyPort);
credentials = credentialsProvider.getCredentials(authScope);
}
credentialsProvider.clear();
if(credentials != null) {
credentialsProvider.setCredentials(authScope, credentials);
}
}
}
示例9: createHttpClient
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
public static AbstractHttpClient createHttpClient()
{
try
{
if (IS_HTTP_CLIENT_GE_4_2)
{
ClientConnectionManager poolingManager = (ClientConnectionManager) Class.forName(
"org.apache.http.impl.conn.PoolingClientConnectionManager").newInstance();
((ConnPoolControl<?>) poolingManager).setMaxTotal(DEFAULT_MAX_TOTAL);
((ConnPoolControl<?>) poolingManager).setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
return new DefaultHttpClient(poolingManager, (HttpParams) null);
} else {
return new ThreadSafeHttpClient();
}
}
catch (Exception e)
{
throw new IllegalStateException("Can not create http client.", e);
}
}
示例10: newClient
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
@Override
protected Client newClient() {
ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder();
ResteasyClient client = resteasyClientBuilder.establishConnectionTimeout(getTimeout(), TimeUnit.MILLISECONDS).socketTimeout(getTimeout(), TimeUnit.MILLISECONDS).build();
AbstractHttpClient httpClient = (AbstractHttpClient) ((ApacheHttpClient4Engine) client.httpEngine()).getHttpClient();
httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(String method) {
return true;
}
});
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
request.setParams(new AllowRedirectHttpParams(request.getParams()));
}
});
return client;
}
示例11: getCookie
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
/**
* 获得cookie
*
* @param httpClient
*/
public static void getCookie(HttpClient httpClient) {
List<Cookie> cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
if (!TextUtils.isEmpty(cookieName)
&& !TextUtils.isEmpty(cookieValue)) {
sb.append(cookieName + "=");
sb.append(cookieValue + ";");
}
}
SharedPreferences.Editor edit = DemoContext.getInstance().getSharedPreferences().edit();
edit.putString("DEMO_COOKIE", sb.toString());
edit.apply();
}
示例12: setProxySettings
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
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()));
}
示例13: getHttpClient
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
/**
* Returns the HttpClient singleton.
*/
public static synchronized HttpClient getHttpClient() {
if (httpClient == null) {
if (AppConfig.DEBUG) Log.d(TAG, "Creating new instance of HTTP client");
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.USER_AGENT, AppPreferences.USER_AGENT);
params.setIntParameter("http.protocol.max-redirects", MAX_REDIRECTS);
params.setBooleanParameter("http.protocol.reject-relative-redirect",
false);
HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
HttpClientParams.setRedirecting(params, true);
httpClient = new DefaultHttpClient(createClientConnectionManager(), params);
// Workaround for broken URLs in redirection
((AbstractHttpClient) httpClient)
.setRedirectHandler(new APRedirectHandler());
}
return httpClient;
}
示例14: get
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
@Override
public HttpClient get() {
AbstractHttpClient client = new DefaultHttpClient() {
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", getHttpsSocketFactory(), 443));
final HttpParams params = getParams();
HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
HttpProtocolParams.setUserAgent(params, getUserAgentString(HttpProtocolParams.getUserAgent(params)));
return new ThreadSafeClientConnManager(params, registry);
}
};
return client;
}
示例15: makeAuthenticationPreemptive
import org.apache.http.impl.client.AbstractHttpClient; //导入依赖的package包/类
/**
*
* This function adds support for pre-emptive HTTP Authentication for an HttpClient.
*
* @param httpClient
*/
public static void makeAuthenticationPreemptive(HttpClient httpClient) {
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
public void process(final HttpRequest request,final HttpContext context) throws HttpException,IOException{
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
((AbstractHttpClient) httpClient).addRequestInterceptor(preemptiveAuth,0);
}