Java Code Examples for org.apache.http.client.CookieStore

The following examples show how to use org.apache.http.client.CookieStore. These examples are extracted from open source projects. 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 Project: docs-apim   Source File: 103335311.java    License: Apache License 2.0 6 votes vote down vote up
public boolean updateToStore(API api, APIStore store) throws APIManagementException {
	boolean updated = false;
    if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) {
        String msg = "External APIStore endpoint URL or credentials are not defined.Cannot proceed with publishing API to the APIStore - " + store.getDisplayName();
        throw new APIManagementException(msg);

    }
    else{
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    boolean authenticated = authenticateAPIM(store, httpContext);
    if (authenticated) {
    	updated = updateWSO2Store(api, store.getUsername(), store.getEndpoint(), httpContext,store.getDisplayName());
    	logoutFromExternalStore(store, httpContext);
    }
    return updated;
    }
}
 
Example 2
Source Project: zerocode   Source File: SslTrustHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method has been overridden here simply to show how a custom/project-specific http client
 * can be plugged into the framework.
 * <p>
 * e.g. You can create your own project specific http client needed for http/https/tls connections.
 * Sometimes you may not need a SSLContext, sometimes you need one, some other times you need a
 * simple default http client e.g. HttpClients.createDefault() provided by Apache.
 * <p>
 * If you do not override this method, the framework creates a http client suitable for both http/https.
 */
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    RequestConfig timeOutConfig = createMaxTimeOutConfig();

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(timeOutConfig)
            .build();
}
 
Example 3
Source Project: TvLauncher   Source File: HttpResult.java    License: Apache License 2.0 6 votes vote down vote up
public HttpResult(HttpResponse httpResponse, CookieStore cookieStore) {
    if (cookieStore != null) {
        this.cookies = cookieStore.getCookies().toArray(new Cookie[0]);
    }

    if (httpResponse != null) {
        this.headers = httpResponse.getAllHeaders();
        this.statuCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println(this.statuCode);
        try {
            this.response = EntityUtils.toByteArray(httpResponse.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 
Example 4
Source Project: vividus   Source File: HttpRequestExecutorTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testExecuteShouldUseCookieStoreFromContext() throws IOException
{
    CookieStore cookieStore = mock(CookieStore.class);
    when(httpTestContext.getCookieStore()).thenReturn(Optional.of(cookieStore));
    HttpResponse httpResponse = mockHttpResponse(URL);
    httpRequestExecutor.executeHttpRequest(HttpMethod.GET, URL, Optional.empty());

    verify(httpClient).execute(argThat(HttpUriRequest.class::isInstance),
            argThat(e -> e != null && e.getAttribute("http.cookie-store") != null));
    InOrder orderedHttpTestContext = inOrder(httpTestContext);
    verifyHttpTestContext(orderedHttpTestContext, httpResponse);
    orderedHttpTestContext.verify(httpTestContext).releaseRequestData();
    orderedHttpTestContext.verifyNoMoreInteractions();
    assertThat(logger.getLoggingEvents(), equalTo(List.of(createResponseTimeLogEvent(httpResponse))));
}
 
Example 5
Source Project: DataSphereStudio   Source File: HttpTest.java    License: 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 6
Source Project: neembuu-uploader   Source File: CookieUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get a string with all the cookies.
 * @param httpContext the context.
 * @param separator the separator string between cookies.
 * @return a new string with all the cookies.
 */
public static String getAllCookies(HttpContext httpContext, String separator){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    String cookieValue;
    StringBuilder result = new StringBuilder();
    for(int i = 0; i < cookies.size(); i++){
        cookieName = cookies.get(i).getName();
        cookieValue = cookies.get(i).getValue();
        result
            .append(cookieName)
            .append("=")
            .append(cookieValue)
            .append(separator);
    }
    return result.toString();
}
 
Example 7
Source Project: zerocode   Source File: CustomHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method has been overridden here simply to show how a custom/project-specific http client
 * can be plugged into the framework.
 *
 * e.g. You can create your own project specific http client needed for http/https/tls connections or
 * a Corporate proxy based Http client here.
 * Sometimes you may need a simple default http client
 * e.g. HttpClients.createDefault() provided by Apache lib.
 *
 * Note:
 * If you do not override this method, the framework anyways creates a http client suitable for both http/https.
 */
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .build();
}
 
Example 8
Source Project: webmagic   Source File: HttpUriRequestConverter.java    License: Apache License 2.0 6 votes vote down vote up
private HttpClientContext convertHttpClientContext(Request request, Site site, Proxy proxy) {
    HttpClientContext httpContext = new HttpClientContext();
    if (proxy != null && proxy.getUsername() != null) {
        AuthState authState = new AuthState();
        authState.update(new BasicScheme(ChallengeState.PROXY), new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
        httpContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, authState);
    }
    if (request.getCookies() != null && !request.getCookies().isEmpty()) {
        CookieStore cookieStore = new BasicCookieStore();
        for (Map.Entry<String, String> cookieEntry : request.getCookies().entrySet()) {
            BasicClientCookie cookie1 = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
            cookie1.setDomain(UrlUtils.removePort(UrlUtils.getDomain(request.getUrl())));
            cookieStore.addCookie(cookie1);
        }
        httpContext.setCookieStore(cookieStore);
    }
    return httpContext;
}
 
Example 9
Source Project: cloudbreak   Source File: FreeIpaClientBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private CloseableHttpResponse execute(HttpPost post, CookieStore cookieStore) throws IOException {
    try (CloseableHttpClient client = HttpClientBuilder
            .create()
            .useSystemProperties()
            .setConnectionManager(connectionManager)
            .setDefaultCookieStore(cookieStore)
            .setConnectionManagerShared(true)
            .setDefaultSocketConfig(
                    SocketConfig.custom()
                            .setSoTimeout(SO_TIMEOUT)
                            .setTcpNoDelay(true)
                            .build())
            .build()) {
        CloseableHttpResponse response = client.execute(post);
        LOGGER.debug("Post response:\n"
                + "code: {}\n"
                + "headers: {}", response.getStatusLine().getStatusCode(), response.getAllHeaders());

        return response;
    }
}
 
Example 10
Source Project: android-tv-launcher   Source File: HttpResult.java    License: MIT License 6 votes vote down vote up
public HttpResult(HttpResponse httpResponse, CookieStore cookieStore) {
	if (cookieStore != null) {
		this.cookies = cookieStore.getCookies().toArray(new Cookie[0]);
	}

	if (httpResponse != null) {
		this.headers = httpResponse.getAllHeaders();
		this.statuCode = httpResponse.getStatusLine().getStatusCode();
		if(d)System.out.println(this.statuCode);
		try {
			this.response = EntityUtils.toByteArray(httpResponse
					.getEntity());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
 
Example 11
Source Project: jeeves   Source File: WechatHttpServiceInternal.java    License: MIT License 6 votes vote down vote up
/**
 * Initialization
 *
 * @param hostUrl     hostUrl
 * @param baseRequest baseRequest
 * @return current user's information and contact information
 * @throws IOException if the http response body can't be convert to {@link InitResponse}
 */
InitResponse init(String hostUrl, BaseRequest baseRequest) throws IOException {
    String url = String.format(WECHAT_URL_INIT, hostUrl, RandomUtils.generateDateWithBitwiseNot());

    CookieStore store = (CookieStore) ((StatefullRestTemplate) restTemplate).getHttpContext().getAttribute(HttpClientContext.COOKIE_STORE);
    Date maxDate = new Date(Long.MAX_VALUE);
    String domain = hostUrl.replaceAll("https://", "").replaceAll("/", "");
    Map<String, String> cookies = new HashMap<>(3);
    cookies.put("MM_WX_NOTIFY_STATE", "1");
    cookies.put("MM_WX_SOUND_STATE", "1");
    appendAdditionalCookies(store, cookies, domain, "/", maxDate);
    InitRequest request = new InitRequest();
    request.setBaseRequest(baseRequest);
    HttpHeaders customHeader = new HttpHeaders();
    customHeader.set(HttpHeaders.REFERER, hostUrl + "/");
    customHeader.setOrigin(hostUrl);
    HeaderUtils.assign(customHeader, postHeader);
    ResponseEntity<String> responseEntity
            = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(request, customHeader), String.class);
    return jsonMapper.readValue(WechatUtils.textDecode(responseEntity.getBody()), InitResponse.class);
}
 
Example 12
Source Project: nexus-public   Source File: NexusITSupport.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return our session cookie; {@code null} if it doesn't exist
 */
@Nullable
protected Cookie getSessionCookie(final CookieStore cookieStore) {
  for (Cookie cookie : cookieStore.getCookies()) {
    if (DEFAULT_SESSION_COOKIE_NAME.equals(cookie.getName())) {
      return cookie;
    }
  }
  return null;
}
 
Example 13
Source Project: instagram4j   Source File: Instagram4j.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param username            Username
 * @param password            Password
 * @param userId              UserId
 * @param uuid                UUID
 * @param cookieStore         Cookie Store
 * @param proxy               proxy
 * @param credentialsProvider proxy credential
 */
@Builder
public Instagram4j(String username, String password, long userId, String uuid, CookieStore cookieStore,
		HttpHost proxy, CredentialsProvider credentialsProvider) {
	super();
	this.username = username;
	this.password = password;
	this.userId = userId;
	this.uuid = uuid;
	this.cookieStore = cookieStore;
	this.proxy = proxy;
	this.credentialsProvider = credentialsProvider;
	this.isLoggedIn = true;
}
 
Example 14
Source Project: commons-vfs   Source File: Http4FileProvider.java    License: Apache License 2.0 5 votes vote down vote up
private CookieStore createDefaultCookieStore(final Http4FileSystemConfigBuilder builder,
        final FileSystemOptions fileSystemOptions) {
    final CookieStore cookieStore = new BasicCookieStore();
    final Cookie[] cookies = builder.getCookies(fileSystemOptions);

    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            cookieStore.addCookie(cookie);
        }
    }

    return cookieStore;
}
 
Example 15
Source Project: qonduit   Source File: HttpClient.java    License: Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

    HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(defaultRequestConfig);
    if (hostVerificationEnabled) {
        builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
    } else {
        builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }
    return builder.build();
}
 
Example 16
Source Project: vividus   Source File: CookieStoreCollector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BinaryOperator<CookieStore> combiner()
{
    return (l, r) ->
    {
        r.getCookies().forEach(l::addCookie);
        return l;
    };
}
 
Example 17
/**
 * This method creates a cookie for every {@link HeaderElement} of the {@link Header} given as parameter.
 * Then, it adds this newly created cookie into the {@link CookieStore} provided as parameter.
 */
protected void createAndAddCookiesOnStoreForHeader(CookieStore cookieStore, Header header) {
    for (HeaderElement element : header.getElements()) {
        BasicClientCookie cookie = createCookieForHeaderElement(element);
        cookieStore.addCookie(cookie);
    }
}
 
Example 18
Source Project: neembuu-uploader   Source File: CookieUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return the name=value of the cookie.
 * @param httpContext HttpContext in which the cookies store
 * @param name the name of the cookie.
 * @return the name and the value of the cookie.
 */
public static String getCookieNameValue(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    Cookie cookie;
    String cookieName;
    for(int i = 0; i < cookies.size(); i++){
        cookie = cookies.get(i);
        cookieName = cookie.getName();
        if(cookieName.contains(name)){
            return cookieName + "=" + cookie.getValue();
        }
    }
    return null;
}
 
Example 19
Source Project: jlitespider   Source File: AsyncNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 设置cookie
 * @param cookies
 */
public void setCookie(Map<String, String> cookies) {
	CookieStore cookieStore = new BasicCookieStore();
	for (Map.Entry<String, String> each : cookies.entrySet()) {
		cookieStore.addCookie(new BasicClientCookie(each.getKey(), each.getValue()));
	}
	httpAsyncClientBuilder.setDefaultCookieStore(cookieStore);
}
 
Example 20
Source Project: browserup-proxy   Source File: NewProxyServerTestUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Creates an all-trusting CloseableHttpClient (for tests ONLY!) that will connect to a proxy at 127.0.0.1:proxyPort,
     * using the specified cookie store.
     *
     * @param proxyPort   port of the proxy running at 127.0.0.1
     * @param cookieStore CookieStore for HTTP cookies
     * @return a new CloseableHttpClient
     */
    public static CloseableHttpClient getNewHttpClient(int proxyPort, CookieStore cookieStore) {
        try {
            // Trust all certs -- under no circumstances should this ever be used outside of testing
//            SSLContext sslcontext = SSLContexts.custom()
//                    .useTLS()
//                    .loadTrustMaterial(null, new TrustStrategy() {
//                        @Override
//                        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//                            return true;
//                        }
//                    })
//                    .build();
//
//            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
//                    sslcontext,
//                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            CloseableHttpClient httpclient = HttpClients.custom()
                    .setDefaultCookieStore(cookieStore)
                    .setProxy(new HttpHost("127.0.0.1", proxyPort))
                    // disable decompressing content, since some tests want uncompressed content for testing purposes
                    .disableContentCompression()
                    .disableAutomaticRetries()
                    .build();

            return httpclient;
        } catch (Exception e) {
            throw new RuntimeException("Unable to create new HTTP client", e);
        }
    }
 
Example 21
Source Project: jeeves   Source File: HttpRestConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public RestTemplate restTemplate() {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG, RequestConfig.custom().setRedirectsEnabled(false).build());
    return new StatefullRestTemplate(httpContext);
}
 
Example 22
Source Project: neembuu-uploader   Source File: CookieUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a cookie from the name.
 * @param httpContext HttpContext in which the cookies store.
 * @param name the name of the cookie.
 * @return the Cookie object.
 */
public static Cookie getCookie(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    Cookie cookie;
    for(int i = 0; i < cookies.size(); i++){
        cookie = cookies.get(i);
        cookieName = cookie.getName();
        if(cookieName.contains(name)){
            return cookie;
        }
    }
    return null;
}
 
Example 23
Source Project: jeeves   Source File: WechatHttpServiceInternal.java    License: MIT License 5 votes vote down vote up
private void appendAdditionalCookies(CookieStore store, Map<String, String> cookies, String domain, String path, Date expiryDate) {
    cookies.forEach((key, value) -> {
        BasicClientCookie cookie = new BasicClientCookie(key, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setExpiryDate(expiryDate);
        store.addCookie(cookie);
    });
}
 
Example 24
/**
 *  For every header that contains the command 'Set-Cookie' it will call the method {@link #createAndAddCookiesOnStoreForHeader(CookieStore, Header)}
 */
protected void createAndAddCookiesOnStoreForHeaders(CookieStore cookieStore, Header[] allHeaders) {
    for (Header header : allHeaders) {
        if (StringUtils.startsWithIgnoreCase(header.getName(), "Set-Cookie")) {
            createAndAddCookiesOnStoreForHeader(cookieStore, header);
        }
    }
}
 
Example 25
Source Project: keycloak   Source File: CookiesPathTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOldCookieWithNodeInValue() throws IOException {
    String requestURI = OAuthClient.AUTH_SERVER_ROOT + "/realms/foo/account";
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, 1);

    // create old cookie with wrong path
    BasicClientCookie wrongCookie = new BasicClientCookie(AuthenticationSessionManager.AUTH_SESSION_ID, AUTH_SESSION_VALUE_NODE);
    wrongCookie.setDomain(AUTH_SERVER_HOST);
    wrongCookie.setPath(OLD_COOKIE_PATH);
    wrongCookie.setExpiryDate(calendar.getTime());

    // obtain new cookies
    CookieStore cookieStore = getCorrectCookies(requestURI);
    cookieStore.addCookie(wrongCookie);

    Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(3));

    login(requestURI, cookieStore);

    // old cookie has been removed
    // now we have AUTH_SESSION_ID, KEYCLOAK_IDENTITY, KEYCLOAK_SESSION, OAuth_Token_Request_State
    Assert.assertThat(cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getName).collect(Collectors.toList()), 
            Matchers.hasItems("AUTH_SESSION_ID", "KEYCLOAK_IDENTITY", "KEYCLOAK_SESSION"));

    // does each cookie's path end with "/"
    cookieStore.getCookies().stream().filter(c -> !"OAuth_Token_Request_State".equals(c.getName())).map(org.apache.http.cookie.Cookie::getPath).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/")));

    // KEYCLOAK_SESSION should end by AUTH_SESSION_ID value
    String authSessionId = cookieStore.getCookies().stream().filter(c -> "AUTH_SESSION_ID".equals(c.getName())).findFirst().get().getValue();
    String KCSessionId = cookieStore.getCookies().stream().filter(c -> "KEYCLOAK_SESSION".equals(c.getName())).findFirst().get().getValue();
    String KCSessionSuffix = KCSessionId.split("/")[2];
    Assert.assertThat(authSessionId, Matchers.containsString(KCSessionSuffix));
}
 
Example 26
Source Project: DataSphereStudio   Source File: HttpTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void  test03() throws IOException, SchedulisSchedulerException {
    Cookie cookie = test01();
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("ajax","fetchProjectPage"));
    params.add(new BasicNameValuePair("start","0"));
    params.add(new BasicNameValuePair("length","10"));
    params.add(new BasicNameValuePair("projectsType","personal"));
    params.add(new BasicNameValuePair("pageNum","1"));
    params.add(new BasicNameValuePair("order","orderProjectName"));
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);
    HttpClientContext context = HttpClientContext.create();
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = null;
    try {
        String finalUrl = "http://127.0.0.1:8088/index" + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params));
        HttpGet httpGet = new HttpGet(finalUrl);
        httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        response = httpClient.execute(httpGet, context);
        /*Header[] allHeaders = context.getRequest().getAllHeaders();
        Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getAppJointName())).findFirst();
        header.ifPresent(AzkabanUtils.handlingConsumerWrapper(this::parseCookie));*/
    } catch (Exception e) {
        throw new SchedulisSchedulerException(90004, e.getMessage());
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
}
 
Example 27
Source Project: onetwo   Source File: HttpClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpClient createHttpClient(CookieStore cookieStore){
	try {
		return createHttpClient0(cookieStore);
	} catch (Exception e) {
		throw new BaseException("create http client error:"+e.getMessage(), e);
	}
}
 
Example 28
Source Project: PicCrawler   Source File: HttpManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取Http客户端连接对象
 * @param timeOut 超时时间
 * @param proxy   代理
 * @param cookie  Cookie
 * @return Http客户端连接对象
 */
private CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) {

    // 创建Http请求配置参数
    RequestConfig.Builder builder = RequestConfig.custom()
            // 获取连接超时时间
            .setConnectionRequestTimeout(timeOut)
            // 请求超时时间
            .setConnectTimeout(timeOut)
            // 响应超时时间
            .setSocketTimeout(timeOut)
            .setCookieSpec(CookieSpecs.STANDARD);

    if (proxy!=null) {
        builder.setProxy(proxy);
    }

    RequestConfig requestConfig = builder.build();

    // 创建httpClient
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder
            // 把请求相关的超时信息设置到连接客户端
            .setDefaultRequestConfig(requestConfig)
            // 把请求重试设置到连接客户端
            .setRetryHandler(new RetryHandler())
            // 配置连接池管理对象
            .setConnectionManager(connManager);

    if (cookie!=null) {
        CookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookie(cookie);
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    return httpClientBuilder.build();
}
 
Example 29
Source Project: DataSphereStudio   Source File: AzkabanProjectService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * parameters:
 * name = value
 * description=value
 *
 * @param project
 * @param session
 * @throws AppJointErrorException
 */
@Override
public Project createProject(Project project, Session session) throws AppJointErrorException {
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("action", "create"));
    params.add(new BasicNameValuePair("name", project.getName()));
    params.add(new BasicNameValuePair("description", project.getDescription()));
    HttpPost httpPost = new HttpPost(projectUrl);
    httpPost.addHeader(HTTP.CONTENT_ENCODING, HTTP.IDENTITY_CODING);
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(session.getCookies()[0]);
    HttpEntity entity = EntityBuilder.create()
            .setContentType(ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))
            .setParameters(params).build();
    httpPost.setEntity(entity);
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    try {
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        response = httpClient.execute(httpPost);
        HttpEntity ent = response.getEntity();
        String entStr = IOUtils.toString(ent.getContent(), "utf-8");
        logger.error("新建工程 {}, azkaban 返回的信息是 {}", project.getName(), entStr);
        String message = AzkabanUtils.handleAzkabanEntity(entStr);
        if (!"success".equals(message)) {
            throw new AppJointErrorException(90008, "新建工程失败, 原因:" + message);
        }
    } catch (Exception e) {
        logger.error("创建工程失败:", e);
        throw new AppJointErrorException(90009, e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
    return null;
}
 
Example 30
Source Project: neembuu-uploader   Source File: CookieUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * There is a cookie with this name?
 * @param httpContext the context.
 * @param name the name of the cookie.
 * @return boolean value.
 */
public static boolean existCookie(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    for(int i = 0; i < cookies.size(); i++){
        cookieName = cookies.get(i).getName();
        if(cookieName.contains(name)){
            return true;
        }
    }
    return false;
}