类org.apache.http.client.CookieStore源码实例Demo

下面列出了怎么用org.apache.http.client.CookieStore的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: docs-apim   文件: 103335311.java
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;
    }
}
 
源代码2 项目: zerocode   文件: SslTrustHttpClient.java
/**
 * 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();
}
 
源代码3 项目: TvLauncher   文件: HttpResult.java
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();
        }
    }

}
 
源代码4 项目: vividus   文件: HttpRequestExecutorTests.java
@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))));
}
 
源代码5 项目: DataSphereStudio   文件: HttpTest.java
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);
}
 
源代码6 项目: neembuu-uploader   文件: CookieUtils.java
/**
 * 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();
}
 
源代码7 项目: zerocode   文件: CustomHttpClient.java
/**
 * 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();
}
 
源代码8 项目: webmagic   文件: HttpUriRequestConverter.java
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;
}
 
源代码9 项目: cloudbreak   文件: FreeIpaClientBuilder.java
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;
    }
}
 
源代码10 项目: android-tv-launcher   文件: HttpResult.java
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();
		}
	}

}
 
源代码11 项目: jeeves   文件: WechatHttpServiceInternal.java
/**
 * 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);
}
 
源代码12 项目: nexus-public   文件: NexusITSupport.java
/**
 * @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;
}
 
源代码13 项目: instagram4j   文件: Instagram4j.java
/**
 * @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;
}
 
源代码14 项目: commons-vfs   文件: Http4FileProvider.java
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;
}
 
源代码15 项目: qonduit   文件: HttpClient.java
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();
}
 
源代码16 项目: vividus   文件: CookieStoreCollector.java
@Override
public BinaryOperator<CookieStore> combiner()
{
    return (l, r) ->
    {
        r.getCookies().forEach(l::addCookie);
        return l;
    };
}
 
/**
 * 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);
    }
}
 
源代码18 项目: canal   文件: HttpHelper.java
private static String getCurlRequest(String url, CookieStore cookieStore, Map<String, String> params, long cost) {
    if (params == null) {
        return "curl '" + url + "'\ncost : " + cost;
    } else {
        StringBuilder paramsStr = new StringBuilder();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            paramsStr.append(entry.getKey() + "=" + entry.getValue());
            if (iterator.hasNext()) {
                paramsStr.append("&");
            }
        }
        if (cookieStore == null) {
            return "curl '" + url + "' -d '" + paramsStr.toString() + "'\ncost : " + cost;
        } else {
            StringBuilder cookieStr = new StringBuilder();
            List<Cookie> cookies = cookieStore.getCookies();
            Iterator<Cookie> iteratorCookie = cookies.iterator();
            while (iteratorCookie.hasNext()) {
                Cookie cookie = iteratorCookie.next();
                cookieStr.append(cookie.getName() + "=" + cookie.getValue());
                if (iteratorCookie.hasNext()) {
                    cookieStr.append(";");
                }
            }
            return "curl '" + url + "' -b '" + cookieStr + "' -d '" + paramsStr.toString() + "'\ncost : " + cost;
        }
    }
}
 
源代码19 项目: neembuu-uploader   文件: CookieUtils.java
/**
 * 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;
}
 
源代码20 项目: jlitespider   文件: AsyncNetwork.java
/**
 * 设置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);
}
 
源代码21 项目: browserup-proxy   文件: NewProxyServerTestUtil.java
/**
     * 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);
        }
    }
 
源代码22 项目: jeeves   文件: HttpRestConfig.java
@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);
}
 
源代码23 项目: neembuu-uploader   文件: CookieUtils.java
/**
 * 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;
}
 
源代码24 项目: jeeves   文件: WechatHttpServiceInternal.java
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);
    });
}
 
/**
 *  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);
        }
    }
}
 
源代码26 项目: keycloak   文件: CookiesPathTest.java
@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));
}
 
源代码27 项目: DataSphereStudio   文件: HttpTest.java
@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);
    }
}
 
源代码28 项目: onetwo   文件: HttpClientUtils.java
public static HttpClient createHttpClient(CookieStore cookieStore){
	try {
		return createHttpClient0(cookieStore);
	} catch (Exception e) {
		throw new BaseException("create http client error:"+e.getMessage(), e);
	}
}
 
源代码29 项目: PicCrawler   文件: HttpManager.java
/**
 * 获取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();
}
 
源代码30 项目: DataSphereStudio   文件: AzkabanProjectService.java
/**
 * 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;
}
 
 类所在包
 同包方法