Java Code Examples for org.apache.http.client.protocol.HttpClientContext#create()

The following examples show how to use org.apache.http.client.protocol.HttpClientContext#create() . 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: RESTServiceConnectorTest.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteRetrieveObjectWithParameters() throws Exception {
    final TestPojo existingObject = new TestPojo();
    existingObject.setField("existingValue");
    final String newObjectJson = gson.toJson(existingObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    final TestPojo object = connector.executeRetrieveObject(TestPojo.class, "/somepath", DEFAULT_TEST_PARAMETERS);

    assertThat(object, notNullValue());
    assertThat(object, equalTo(existingObject));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
    verify(response).close();
}
 
Example 2
Source File: RESTServiceConnectorTest.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteCreateObjectWithParameters() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    final TestPojo object = connector.executeCreateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);

    assertThat(object, notNullValue());
    assertThat(object, equalTo(newObject));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
    verify(response).close();
}
 
Example 3
Source File: TestSecureRESTServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
private Pair<CloseableHttpClient,HttpClientContext> getClient() {
  HttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
  HttpHost host = new HttpHost("localhost", REST_TEST.getServletPort());
  Registry<AuthSchemeProvider> authRegistry =
      RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
          new SPNegoSchemeFactory(true, true)).build();
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
  AuthCache authCache = new BasicAuthCache();

  CloseableHttpClient client = HttpClients.custom()
      .setDefaultAuthSchemeRegistry(authRegistry)
      .setConnectionManager(pool).build();

  HttpClientContext context = HttpClientContext.create();
  context.setTargetHost(host);
  context.setCredentialsProvider(credentialsProvider);
  context.setAuthSchemeRegistry(authRegistry);
  context.setAuthCache(authCache);

  return new Pair<>(client, context);
}
 
Example 4
Source File: SonarHttpRequesterFactory.java    From sonar-quality-gates-plugin with MIT License 6 votes vote down vote up
static SonarHttpRequester getSonarHttpRequester(GlobalConfigDataForSonarInstance globalConfigDataForSonarInstance) {

        try {
            HttpGet request = new HttpGet(getSonarApiServerVersion(globalConfigDataForSonarInstance));

            HttpClientContext context = HttpClientContext.create();
            CloseableHttpClient client = HttpClientBuilder.create().build();
            CloseableHttpResponse response = client.execute(request, context);
            String sonarVersion = EntityUtils.toString(response.getEntity());

            if (majorSonarVersion(sonarVersion) <= 5) {
                return new SonarHttpRequester5x();
            } else if (majorSonarVersion(sonarVersion) >= 6 && minorSonarVersion(sonarVersion) == 0) {
                return new SonarHttpRequester60();
            } else if (majorSonarVersion(sonarVersion) >= 6 && minorSonarVersion(sonarVersion) >= 1) {
                return new SonarHttpRequester61();
            } else {
                throw new UnsuportedVersionException("Plugin doesn't suport this version of sonar api! Please contact the developer.");
            }
        } catch (IOException e) {
            throw new ApiConnectionException(e.getLocalizedMessage());
        }
    }
 
Example 5
Source File: RESTServiceConnectorTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteUpdateObjectWithParameters() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");

    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    connector.executeUpdateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);

    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
}
 
Example 6
Source File: HttpTest.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
public Cookie test01() throws IOException {
    HttpPost httpPost = new HttpPost("http://127.0.0.1:8088/checkin");
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("username", "neiljianliu"));
    params.add(new BasicNameValuePair("userpwd", "*****"));
    params.add(new BasicNameValuePair("action", "login"));
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    CookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    HttpClientContext context = null;
    try {
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        context = HttpClientContext.create();
        response = httpClient.execute(httpPost, context);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
    List<Cookie> cookies = context.getCookieStore().getCookies();
    return cookies.get(0);
}
 
Example 7
Source File: GeoServerIT.java    From geowave with Apache License 2.0 6 votes vote down vote up
protected static Pair<CloseableHttpClient, HttpClientContext> createClientAndContext() {
  final CredentialsProvider provider = new BasicCredentialsProvider();
  provider.setCredentials(
      new AuthScope("localhost", ServicesTestEnvironment.JETTY_PORT),
      new UsernamePasswordCredentials(
          ServicesTestEnvironment.GEOSERVER_USER,
          ServicesTestEnvironment.GEOSERVER_PASS));
  final AuthCache authCache = new BasicAuthCache();
  final HttpHost targetHost =
      new HttpHost("localhost", ServicesTestEnvironment.JETTY_PORT, "http");
  authCache.put(targetHost, new BasicScheme());

  // Add AuthCache to the execution context
  final HttpClientContext context = HttpClientContext.create();
  context.setCredentialsProvider(provider);
  context.setAuthCache(authCache);
  return ImmutablePair.of(
      HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(),
      context);
}
 
Example 8
Source File: HttpUtil.java    From ZhihuSpider with MIT License 5 votes vote down vote up
public static HttpClientContext getHttpClientContext() {
    HttpClientContext context = null;
    context = HttpClientContext.create();
    Registry<CookieSpecProvider> registry = RegistryBuilder
            .<CookieSpecProvider>create()
            .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
            .register(CookieSpecs.BROWSER_COMPATIBILITY,
                    new BrowserCompatSpecFactory()).build();
    context.setCookieSpecRegistry(registry);
    return context;
}
 
Example 9
Source File: JavaBrokerAdmin.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private HttpClientContext getHttpClientContext(final HttpHost management)
{
    final BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(management, new BasicScheme());
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
 
Example 10
Source File: RESTServiceConnectorTest.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Test(expected = JsonParseException.class)
public void testCustomDeserializerTypeMismatch() throws Exception {
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    when(response.getEntity()).thenReturn(new StringEntity("[{somethig_not_type : \"WrongType\"}]"));
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder()
            .client(restClient)
            .classToDeserializerEntry(TestPojo.class, new TestPojoDeserializer())
            .build();

    connector.executeRetrieveObject(TestPojo.class, "/somepath");
}
 
Example 11
Source File: LibraryUtil.java    From newblog with Apache License 2.0 5 votes vote down vote up
private static void init() {
    context = HttpClientContext.create();
    cookieStore = new BasicCookieStore();
    // 配置超时时间(连接服务端超时1秒,请求数据返回超时2秒)
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)
            .setConnectionRequestTimeout(60000).build();
    // 设置默认跳转以及存储cookie
    httpClient = HttpClientBuilder.create()
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
            .setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig)
            .setDefaultCookieStore(cookieStore).build();
}
 
Example 12
Source File: AsyncClientCustomContext.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public final static void main(String[] args) throws Exception {
	CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	try {
		// Create a local instance of cookie store
		CookieStore cookieStore = new BasicCookieStore();

		// Create local HTTP context
		HttpClientContext localContext = HttpClientContext.create();
		// Bind custom cookie store to the local context
		localContext.setCookieStore(cookieStore);

           HttpGet httpget = new HttpGet("http://localhost/");
		System.out.println("Executing request " + httpget.getRequestLine());

		httpclient.start();

		// Pass local context as a parameter
		Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

		// Please note that it may be unsafe to access HttpContext instance
		// while the request is still being executed

		HttpResponse response = future.get();
		System.out.println("Response: " + response.getStatusLine());
		List<Cookie> cookies = cookieStore.getCookies();
		for (int i = 0; i < cookies.size(); i++) {
			System.out.println("Local cookie: " + cookies.get(i));
		}
		System.out.println("Shutting down");
	} finally {
		httpclient.close();
	}
}
 
Example 13
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://uac.10010.com/portal/Service/SendMSG?callback=jQuery17205929719702722311_1528559748925&req_time=1528560335346&mobile=13249073372&_=1528560335347
 * @throws Exception 
 * @throws ParseException 
 */
@Test
public void sendSms() throws ParseException, Exception {
	CookieStore cookie = new BasicCookieStore() ;
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookie);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("req_time", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("_=", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("mobile", Lists.newArrayList("13249073372"));
	String url = UriComponentsBuilder.fromHttpUrl("https://uac.10010.com/portal/Service/SendMSG").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
	System.out.println("cookie:" + JSON.toJSONString(cookie));
	
}
 
Example 14
Source File: HttpComponentsAsyncClientHttpRequestFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
	HttpAsyncClient client = startAsyncClient();

	HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
	postProcessHttpRequest(httpRequest);
	HttpContext context = createHttpContext(httpMethod, uri);
	if (context == null) {
		context = HttpClientContext.create();
	}

	// Request configuration not set in the context
	if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
		// Use request configuration given by the user, when available
		RequestConfig config = null;
		if (httpRequest instanceof Configurable) {
			config = ((Configurable) httpRequest).getConfig();
		}
		if (config == null) {
			config = createRequestConfig(client);
		}
		if (config != null) {
			context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
		}
	}

	return new HttpComponentsAsyncClientHttpRequest(client, httpRequest, context);
}
 
Example 15
Source File: HttpComponentsConnector.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
public HttpComponentsConnector(final CloseableHttpClient client, final Configuration runtimeConfig) {
    this.client = client;
    this.context = HttpClientContext.create();
}
 
Example 16
Source File: HttpUtils.java    From yuzhouwan with Apache License 2.0 4 votes vote down vote up
/**
 * HttpClient 上下文.
 */
private void httpClientContext() {
    httpClientContext = HttpClientContext.create();
    httpClientContext.setCookieStore(new BasicCookieStore());
}
 
Example 17
Source File: BintrayImpl.java    From bintray-client-java with Apache License 2.0 4 votes vote down vote up
public RequestRunner(HttpRequestBase request, CloseableHttpClient client, ResponseHandler<HttpResponse> responseHandler) {
    this.request = request;
    this.client = client;
    this.context = HttpClientContext.create();
    this.responseHandler = responseHandler;
}
 
Example 18
Source File: DefaultBotOptions.java    From TelegramBots with MIT License 4 votes vote down vote up
public DefaultBotOptions() {
    maxThreads = 1;
    baseUrl = ApiConstants.BASE_URL;
    httpContext = HttpClientContext.create();
    proxyType = ProxyType.NO_PROXY;
}
 
Example 19
Source File: HttpAsyncClientLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
    this.client = client;
    context = HttpClientContext.create();
    this.request = request;
}
 
Example 20
Source File: NexusITSupport.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @return Context with preemptive auth enabled for Nexus
 */
protected HttpClientContext clientContext() {
  HttpClientContext context = HttpClientContext.create();
  context.setAuthCache(basicAuthCache());
  return context;
}