org.apache.http.client.CookieStore Java Examples

The following examples show how to use org.apache.http.client.CookieStore. 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: 103335311.java    From docs-apim with 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 File: HttpResult.java    From android-tv-launcher with 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 #3
Source File: SslTrustHttpClient.java    From zerocode with 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 #4
Source File: CustomHttpClient.java    From zerocode with 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 #5
Source File: HttpUriRequestConverter.java    From webmagic with 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 #6
Source File: FreeIpaClientBuilder.java    From cloudbreak with 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 #7
Source File: WechatHttpServiceInternal.java    From jeeves with 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 #8
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 #9
Source File: HttpRequestExecutorTests.java    From vividus with 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 #10
Source File: CookieUtils.java    From neembuu-uploader with 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 #11
Source File: HttpResult.java    From TvLauncher with 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 #12
Source File: CookieUtils.java    From neembuu-uploader with 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 #13
Source File: CookiesPathTest.java    From keycloak with 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 #14
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 5 votes vote down vote up
/**
 *  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 #15
Source File: WechatHttpServiceInternal.java    From jeeves with 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 #16
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #17
Source File: HttpRestConfig.java    From jeeves with 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 #18
Source File: NewProxyServerTestUtil.java    From browserup-proxy with 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 #19
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a cookie value from the name. If the cookie starts with the name, you'll get this value.
 * @param httpContext HttpContext in which the cookies store
 * @param name the first part of the name of the cookie.
 * @return the String cookie.
 */
public static String getCookieStartsWithValue(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.startsWith(name)){
            return cookies.get(i).getValue();
        }
    }
    return null;
}
 
Example #20
Source File: HttpTest.java    From DataSphereStudio with 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 #21
Source File: HttpClientUtils.java    From onetwo with 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 #22
Source File: HttpManager.java    From PicCrawler with 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 #23
Source File: AzkabanProjectService.java    From DataSphereStudio with 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 #24
Source File: CookieUtils.java    From neembuu-uploader with 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;
}
 
Example #25
Source File: HttpHelper.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
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;
        }
    }
}
 
Example #26
Source File: NexusITSupport.java    From nexus-public with 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(CookieStore cookieStore) {
  for (Cookie cookie : cookieStore.getCookies()) {
    if (DEFAULT_SESSION_COOKIE_NAME.equals(cookie.getName())) {
      return cookie;
    }
  }
  return null;
}
 
Example #27
Source File: DefaultHttpClientTemplate.java    From simple-robot-core with Apache License 2.0 5 votes vote down vote up
/**
 * map转化为cookieStore
 *
 * @param cookies cookies
 */
private static CookieStore toCookieStore(Map<String, String> cookies) {
    CookieStore cookieStore = new BasicCookieStore();
    cookies.entrySet().stream()
            .map(e -> new BasicClientCookie(e.getKey(), e.getValue()))
            .forEach(cookieStore::addCookie);
    return cookieStore;
}
 
Example #28
Source File: HttpRequest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected String getAPITokenFromCookie() {
    final CookieStore cookieStore = httpClientFactory.getCookieStore();
    return find(cookieStore.getCookies(), new Predicate<Cookie>() {

        @Override
        public boolean apply(Cookie c) {
            return Objects.equals(c.getName(), API_TOKEN_HEADER);
        }

    }).getValue();
}
 
Example #29
Source File: DefaultHttpClientTemplate.java    From simple-robot-core with Apache License 2.0 5 votes vote down vote up
/**
 * 使用post的方式进行网络请求
 * 一般header中会提供一些json或者from的参数
 *
 * @param url     送信网络路径
 * @param params  参数列表,默认为空map,可以为null
 * @param cookies 所携带的cookie列表,默认为空map,可以为null
 * @param header  头信息,默认为空map,可以为null
 * @return 网页的返回值字符串
 */
@Override
public String post(String url, String params, Map<String, String> cookies, Map<String, String> header) {
    cookies = cookies == null ? new HashMap<>(1) : cookies;
    header = header == null ? new HashMap<>(1) : header;
    String response = null;

    try {
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        // 获取domain
        final String domain = httpPost.getURI().getAuthority();

        // 设置cookie
        CookieStore cookieStore;
        if (!cookies.isEmpty()) {
            cookieStore = toCookieStore(domain, cookies, baseCookieStore);
        } else {
            cookieStore = baseCookieStore;
        }

        // 存在参数, 设置参数
        if (params != null && params.trim().length() > 0) {
            StringEntity entity = new StringEntity(params, CHARSET_UTF_8);
            httpPost.setEntity(entity);
        }


        // 添加头信息
        addHeaders(httpPost, header);

        // 发送请求
        CloseableHttpClient httpClient = getHttpClient(cookieStore);
        response = send(httpClient, httpPost);
    } catch (Exception e) {
        throw new DefaultHttpClientException(e);
    }
    return response;
}
 
Example #30
Source File: DefaultHttpClientTemplate.java    From simple-robot-core with Apache License 2.0 5 votes vote down vote up
/**
 * 使用get的方式进行网络请求
 *
 * @param url     送信网络路径
 * @param params  参数列表,默认为空map,可以为null
 * @param cookies 所携带的cookie列表,默认为空map,可以为null
 * @param header  头信息,默认为空map,可以为null
 * @return 网页的返回值字符串
 */
@Override
public String get(String url, Map<String, String> params, Map<String, String> cookies, Map<String, String> header) {
    params = params == null ? new HashMap<>(1) : params;
    cookies = cookies == null ? new HashMap<>(1) : cookies;
    header = header == null ? new HashMap<>(1) : header;
    if(!header.containsKey(USER_AGENT_KEY_NAME)){
        header.put(USER_AGENT_KEY_NAME, USER_AGENT_WIN10_CHROME);
    }


    String response = null;
    try {
        // 创建URI
        URI uri = getURI(url, params);

        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);
        // 获取domain
        final String domain = httpGet.getURI().getAuthority();
        // 设置cookie
        CookieStore cookieStore;
        if (!cookies.isEmpty()) {
            cookieStore = toCookieStore(domain, cookies, baseCookieStore);
        } else {
            cookieStore = baseCookieStore;
        }

        // 设置请求头
        addHeaders(httpGet, header);

        // 发送请求
        CloseableHttpClient httpClient = getHttpClient(cookieStore);
        response = send(httpClient, httpGet);
    } catch (Exception e) {
        throw new DefaultHttpClientException(e);
    }
    return response;
}