本文整理汇总了Java中org.apache.http.protocol.BasicHttpContext类的典型用法代码示例。如果您正苦于以下问题:Java BasicHttpContext类的具体用法?Java BasicHttpContext怎么用?Java BasicHttpContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BasicHttpContext类属于org.apache.http.protocol包,在下文中一共展示了BasicHttpContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
public static void main(String... args) throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
List<String> authpref = new ArrayList<String>();
authpref.add(AuthPolicy.NTLM);
httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
NTCredentials creds = new NTCredentials("abhisheks", "abhiProJul17", "", "");
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HttpHost target = new HttpHost("apps.prorigo.com", 80, "http");
// Make sure the same context is used to execute logically related requests
HttpContext localContext = new BasicHttpContext();
// Execute a cheap method first. This will trigger NTLM authentication
HttpGet httpget = new HttpGet("/conference/Booking");
HttpResponse response = httpclient.execute(target, httpget, localContext);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
}
示例2: getModSlug0
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
@Nullable
private String getModSlug0(int id)
{
try
{
log.debug("Getting mod slug from server...");
URI uri = getURI(CURSEFORGE_URL, String.format(PROJECT_PATH, id), null);
HttpGet request = new HttpGet(uri.toURL().toString());
HttpContext context = new BasicHttpContext();
HttpResponse response = http.execute(request, context);
EntityUtils.consume(response.getEntity());
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
Splitter splitter = Splitter.on('/').omitEmptyStrings();
List<String> pathParts = splitter.splitToList(currentUrl);
return pathParts.get(pathParts.size() - 1);
}
catch (Exception e)
{
log.error("Failed to perform request from CurseForge site.", e);
return null;
}
}
示例3: getHttpClient
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
public QMailHttpClient getHttpClient() throws MessagingException {
if (httpClient == null) {
httpClient = httpClientFactory.create();
// Disable automatic redirects on the http client.
httpClient.getParams().setBooleanParameter("http.protocol.handle-redirects", false);
// Setup a cookie store for forms-based authentication.
httpContext = new BasicHttpContext();
authCookies = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, authCookies);
SchemeRegistry reg = httpClient.getConnectionManager().getSchemeRegistry();
try {
Scheme s = new Scheme("https", new WebDavSocketFactory(hostname, 443), 443);
reg.register(s);
} catch (NoSuchAlgorithmException nsa) {
Timber.e(nsa, "NoSuchAlgorithmException in getHttpClient");
throw new MessagingException("NoSuchAlgorithmException in getHttpClient: ", nsa);
} catch (KeyManagementException kme) {
Timber.e(kme, "KeyManagementException in getHttpClient");
throw new MessagingException("KeyManagementException in getHttpClient: ", kme);
}
}
return httpClient;
}
示例4: read
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
/**
* Returns the content read form content-source.
* @return read {@link Content}
*/
@Override
public Content[] read(final FetchHistory lastFetch) {
final CloseableHttpClient httpClient = HttpClients.createDefault();
final HttpGet httpget = new HttpGet(contentSource.getUrl());
final HttpContext context = new BasicHttpContext();
CloseableHttpResponse response = null;
String stringRead = null;
try {
try {
LOGGER.info("Loading uri: " + httpget.getURI());
response = httpClient.execute(httpget, context);
final HttpEntity entity = response.getEntity();
if (entity != null) {
stringRead = IOUtils.toString(entity.getContent());
LOGGER.info("Read {} bytes from: {}", stringRead.getBytes().length, httpget.getURI());
}
} finally {
CloseUtil.close(response);
CloseUtil.close(httpClient);
}
} catch (final Exception e) {
LOGGER.warn("Error occurred while reading text document: " + contentSource.getUrl());
}
return new Content[] { createContentObject(stringRead) };
}
示例5: execute
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
public HttpResponse execute(HttpRequest request) throws IOException, HttpException {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProcessor processor = new ImmutableHttpProcessor(new RequestContent());
HttpRequestExecutor executor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, connection);
if (!connection.isOpen()) {
Socket socket = new Socket(address.getAddress(), address.getPort());
connection.bind(socket, params);
}
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
request.setParams(params);
executor.preProcess(request, processor, context);
HttpResponse response = executor.execute(request, connection, context);
executor.postProcess(response, processor, context);
return response;
}
示例6: createHttpContext
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
protected HttpContext createHttpContext() {
HttpContext context = new BasicHttpContext();
context.setAttribute(
ClientContext.SCHEME_REGISTRY,
getConnectionManager().getSchemeRegistry());
context.setAttribute(
ClientContext.AUTHSCHEME_REGISTRY,
getAuthSchemes());
context.setAttribute(
ClientContext.COOKIESPEC_REGISTRY,
getCookieSpecs());
context.setAttribute(
ClientContext.COOKIE_STORE,
getCookieStore());
context.setAttribute(
ClientContext.CREDS_PROVIDER,
getCredentialsProvider());
return context;
}
示例7: logsRequestAndResponseFields
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
@Test
public void logsRequestAndResponseFields() {
HttpContext context = new BasicHttpContext();
context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com");
OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor(new FakeClock(20));
interceptor.process(new BasicHttpRequest("GET", "/something"), context);
interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context);
Map<String, Object> fields = new ConcurrentHashMap<>();
fields.put("requestMethod", "GET");
fields.put("requestURI", "http://www.google.com/something");
testAppender.assertEvent(0, INFO, "Outbound request start", appendEntries(fields));
fields.put("responseTime", 20L);
fields.put("responseCode", 200);
testAppender.assertEvent(1, INFO, "Outbound request finish", appendEntries(fields));
}
示例8: allowEmptyConstructorToBuildDefaultClock
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
@Test
public void allowEmptyConstructorToBuildDefaultClock() {
testAppender.clearEvents();
HttpContext context = new BasicHttpContext();
context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com");
OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor();
interceptor.process(new BasicHttpRequest("GET", "/something"), context);
interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context);
assertThat(testAppender.getEvents()).extracting("message")
.contains("Outbound request start", Index.atIndex(0))
.contains("Outbound request finish", Index.atIndex(1));
}
示例9: testManualParentSpan
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
@Test
public void testManualParentSpan() throws IOException {
MockSpan parent = mockTracer.buildSpan("parent")
.startManual();
{
ActiveSpan parentSpan = mockTracer.buildSpan("parent")
.startActive();
HttpContext context = new BasicHttpContext();
context.setAttribute(Constants.PARENT_CONTEXT, parent.context());
CloseableHttpClient client = clientBuilder.build();
client.execute(new HttpGet(serverUrl("/echo/a")), context);
}
List<MockSpan> mockSpans = mockTracer.finishedSpans();
Assert.assertEquals(2, mockSpans.size());
Assert.assertEquals(parent.context().traceId(), mockSpans.get(1).context().traceId());
Assert.assertEquals(parent.context().spanId(), mockSpans.get(1).parentId());
assertLocalSpan(mockSpans.get(1));
}
开发者ID:opentracing-contrib,项目名称:java-apache-httpclient,代码行数:25,代码来源:TracingHttpClientBuilderTest.java
示例10: StatefullRestTemplate
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
StatefullRestTemplate(HttpContext httpContext) {
super();
HttpClient httpClient = HttpClientBuilder.create().build();
this.httpContext = httpContext == null ? new BasicHttpContext() : httpContext;
StatefullHttpComponentsClientHttpRequestFactory statefullHttpComponentsClientHttpRequestFactory
= new StatefullHttpComponentsClientHttpRequestFactory(httpClient, httpContext);
super.setRequestFactory(statefullHttpComponentsClientHttpRequestFactory);
List<HttpMessageConverter<?>> converters = this.getMessageConverters();
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
List<MediaType> mediaTypes = converter.getSupportedMediaTypes();
List<MediaType> newMediaTypes = new ArrayList<>(mediaTypes);
newMediaTypes.add(MediaType.TEXT_HTML);
((MappingJackson2HttpMessageConverter) converter).setSupportedMediaTypes(newMediaTypes);
}
}
}
示例11: downloadHTTPfile_post
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
private byte[] downloadHTTPfile_post(String formToDownloadLocation, List<NameValuePair> params) throws IOException, NullPointerException, URISyntaxException {
BasicHttpContext localContext = new BasicHttpContext();
LOG.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
if (this.mimicWebDriverCookieState) {
localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies()));
}
HttpPost httppost = new HttpPost(formToDownloadLocation);
HttpParams httpRequestParameters = httppost.getParams();
httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
httppost.setParams(httpRequestParameters);
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
LOG.info("Sending POST request for: " + httppost.getURI());
@SuppressWarnings("resource")
HttpResponse response = new DefaultHttpClient().execute(httppost, localContext);
this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
byte[] file = IOUtils.toByteArray(response.getEntity().getContent());
response.getEntity().getContent().close();
return file;
}
示例12: testProxy
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
@Test
public void testProxy() throws Exception {
final InetAddress ia = InetAddress.getByAddress(new byte[] {
(byte)127, (byte)0, (byte)0, (byte)1
});
final InetSocketAddress isa1 = new InetSocketAddress(ia, 11111);
final InetSocketAddress isa2 = new InetSocketAddress(ia, 22222);
final List<Proxy> proxies = new ArrayList<Proxy>(2);
proxies.add(new Proxy(Proxy.Type.HTTP, isa1));
proxies.add(new Proxy(Proxy.Type.HTTP, isa2));
Mockito.when(proxySelector.select(new URI("http://somehost:80"))).thenReturn(proxies);
final HttpHost target = new HttpHost("somehost", 80, "http");
final HttpRequest request =
new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);
final HttpContext context = new BasicHttpContext();
final HttpRoute route = routePlanner.determineRoute(target, request, context);
Assert.assertEquals(target, route.getTargetHost());
Assert.assertEquals(2, route.getHopCount());
Assert.assertEquals(isa1.getPort(), route.getProxyHost().getPort());
}
示例13: sendPost
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
/**
* 向指定URL发送POST方法的数据请求.
*
* @param url 发送请求的URL
* @param params 请求参数k1=v1&k2=v2
* @param encode 编码格式
* @param isProxy 是否使用代理
* @return
*/
public static String sendPost(String url, String params, String encode, boolean isProxy) {
SafeHttpClient httpClient = HttpClientFactory.getHttpClient(isProxy);
HttpPost httpReq = new HttpPost(url);
try {
if (StringUtils.isNotBlank(params)) {
// 构造最简单的字符串数据
StringEntity reqEntity = new StringEntity(params);
reqEntity.setContentType("application/x-www-form-urlencoded");
// 设置请求的数据
httpReq.setEntity(reqEntity);
}
ResponseHandler<String> responseHandler = new SimpleResponseHandler(encode);
return httpClient.execute(httpReq, responseHandler, new BasicHttpContext());
} catch (Exception e) {
LOGGER.error("POST请求远程地址失败,url:{},params:{},encode:{},isProxy:{},Exception:{}", url, params, encode,
isProxy, ExceptionUtil.getException(e));
httpReq.abort();
httpClient.closeExpiredConnections();
}
return null;
}
示例14: sendGetBytes
import org.apache.http.protocol.BasicHttpContext; //导入依赖的package包/类
/**
* 获取远程数据bytes
*
* @param url 发送请求的URL
* @param isProxy 是否使用代理
* @return
*/
public static byte[] sendGetBytes(String url, boolean isProxy) {
SafeHttpClient httpClient = HttpClientFactory.getHttpClient(isProxy);
HttpUriRequest httpReq = new HttpGet(url);
try {
HttpContext context = new BasicHttpContext();
ResponseHandler<byte[]> responseHandler = new BytesResponseHandler();
return httpClient.execute(httpReq, responseHandler, context);
} catch (Exception e) {
LOGGER.error("sendGetBytes请求远程地址失败,url:{},encode:{},Exception:{}", url, isProxy,
ExceptionUtil.getException(e));
httpReq.abort();
httpClient.closeExpiredConnections();
}
return null;
}
示例15: execute
import org.apache.http.protocol.BasicHttpContext; //导入依赖的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;
}