本文整理匯總了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;
}