Java Code Examples for java.net.CookieManager#setCookiePolicy()

The following examples show how to use java.net.CookieManager#setCookiePolicy() . 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: RestClient.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Creates an instance of the builder with a base URL and 2 custom builders.
 *
 * @param httpClientBuilder the builder to build an {@link OkHttpClient}.
 * @param retrofitBuilder the builder to build a {@link Retrofit}.
 */
public Builder(OkHttpClient.Builder httpClientBuilder, Retrofit.Builder retrofitBuilder) {
    if (httpClientBuilder == null) {
        throw new IllegalArgumentException("httpClientBuilder == null");
    }
    if (retrofitBuilder == null) {
        throw new IllegalArgumentException("retrofitBuilder == null");
    }
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    customHeadersInterceptor = new CustomHeadersInterceptor();
    // Set up OkHttp client
    this.httpClientBuilder = httpClientBuilder
            .cookieJar(new JavaNetCookieJar(cookieManager))
            .readTimeout(120, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(new RequestIdHeaderInterceptor())
            .addInterceptor(new BaseUrlHandler());
    this.retrofitBuilder = retrofitBuilder;
    this.loggingInterceptor = new LoggingInterceptor(LogLevel.NONE);
    this.useHttpClientThreadPool = false;
}
 
Example 2
Source File: RestClient.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Creates an instance of the builder with a base URL and 2 custom builders.
 *
 * @param httpClientBuilder the builder to build an {@link OkHttpClient}.
 * @param retrofitBuilder the builder to build a {@link Retrofit}.
 */
public Builder(OkHttpClient.Builder httpClientBuilder, Retrofit.Builder retrofitBuilder) {
    if (httpClientBuilder == null) {
        throw new IllegalArgumentException("httpClientBuilder == null");
    }
    if (retrofitBuilder == null) {
        throw new IllegalArgumentException("retrofitBuilder == null");
    }
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    customHeadersInterceptor = new CustomHeadersInterceptor();
    // Set up OkHttp client
    this.httpClientBuilder = httpClientBuilder
            .cookieJar(new JavaNetCookieJar(cookieManager))
            .readTimeout(120, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(new RequestIdHeaderInterceptor())
            .addInterceptor(new BaseUrlHandler());
    this.retrofitBuilder = retrofitBuilder;
    this.loggingInterceptor = new LoggingInterceptor(LogLevel.NONE);
    this.useHttpClientThreadPool = false;
}
 
Example 3
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        /*
        HttpClient client = HttpClient.newBuilder()
                .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
                .build();

        System.out.println(client.cookieHandler().orElseThrow());
         */
        
        CookieManager cm = new CookieManager();
        cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        
        HttpClient client = HttpClient.newBuilder()
                .cookieHandler(cm)
                .build();

        HttpRequest request = HttpRequest.newBuilder()
                .header("Authorization", "Bearer Q3ku4mp_hCQGvAFeYKa0ktFCDKS3VpSA1nwf")                
                .uri(URI.create("https://gorest.co.in/public-api/users/1"))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());       
        System.out.println("\nset-cookie header: " + response.headers().firstValue("set-cookie"));
        
        CookieStore cookieStore = cm.getCookieStore();
        
        System.out.println("\nCookies: " + cookieStore.getCookies());
    }
 
Example 4
Source File: PlayerProviderImpl.java    From ARVI with Apache License 2.0 5 votes vote down vote up
private void initCookieManager() {
    // Adapt from ExoPlayer demo app. Start this on demand.
    final CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);

    if(CookieHandler.getDefault() != cookieManager) {
        CookieHandler.setDefault(cookieManager);
    }
}
 
Example 5
Source File: Cloudflare.java    From cloudflare-scrape-Android with MIT License 4 votes vote down vote up
private void urlThread(cfCallback callback){
    mCookieManager = new CookieManager();
    mCookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); //接受所有cookies
    CookieHandler.setDefault(mCookieManager);
    HttpURLConnection.setFollowRedirects(false);
    while (!canVisit){
        if (mRetry_count>MAX_COUNT){
            break;
        }
        try {

            int responseCode = checkUrl();
            if (responseCode==200){
                canVisit=true;
                break;
            }else {
                getVisitCookie();
            }
        } catch (IOException | RuntimeException | InterruptedException e) {
            if (mCookieList!=null){
                mCookieList= new ArrayList<>(mCookieList);
                mCookieList.clear();
            }
            e.printStackTrace();
        } finally {
            closeAllConn();
        }
        mRetry_count++;
    }
    if (callback!=null){
        Looper.prepare();
        if (canVisit){
            callback.onSuccess(mCookieList,hasNewUrl,mUrl);
        }else {
            e("Get Cookie Failed");
            callback.onFail("Retries exceeded the limit");
        }


    }
}
 
Example 6
Source File: Cloudflare.java    From cloudflare-scrape-Android with MIT License 4 votes vote down vote up
private void urlThread(cfCallback callback){
    mCookieManager = new CookieManager();
    mCookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); //接受所有cookies
    CookieHandler.setDefault(mCookieManager);
    HttpURLConnection.setFollowRedirects(false);
    while (!canVisit){
        if (mRetry_count>MAX_COUNT){
            break;
        }
        try {

            int responseCode = checkUrl();
            if (responseCode==200){
                canVisit=true;
                break;
            }else {
                getVisitCookie();
            }
        } catch (IOException| RuntimeException | InterruptedException e) {
            if (mCookieList!=null){
                mCookieList= new ArrayList<>(mCookieList);
                mCookieList.clear();
            }
            e.printStackTrace();
        } finally {
            closeAllConn();
        }
        mRetry_count++;
    }
    if (callback!=null){
        Looper.prepare();
        if (canVisit){
            callback.onSuccess(mCookieList,hasNewUrl,mUrl);
        }else {
            e("Get Cookie Failed");
            callback.onFail("Retries exceeded the limit");
        }


    }
}
 
Example 7
Source File: HttpClient.java    From StubbornJava with MIT License 4 votes vote down vote up
public static OkHttpClient newClientWithCookieJar() {
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
    return client.newBuilder().cookieJar(cookieJar).build();
}
 
Example 8
Source File: SHelper.java    From Xndroid with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @see "http://blogs.sun.com/CoreJavaTechTips/entry/cookie_handling_in_java_se"
 */
public static void enableCookieMgmt() {
    CookieManager manager = new CookieManager();
    manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);
}
 
Example 9
Source File: HttpClient.java    From secrets-proxy with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a {@link OkHttpClient} to start a TLS connection. The OKHttp logging is enabled if the
 * debug log is enabled for {@link HttpClient}.
 */
protected OkHttpClient createHttpsClient() throws GeneralSecurityException {
  TrustManager[] trustManagers = keywhizKeyStore.getTrustManagers();
  KeyManager[] keyManagers = loadKeyMaterial();
  SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
  sslContext.init(keyManagers, trustManagers, new SecureRandom());
  SSLSocketFactory socketFactory = sslContext.getSocketFactory();
  log.info("Keywhiz connect timeout " + keywhiz.getClientTimeout());

  HttpLoggingInterceptor loggingInterceptor =
      new HttpLoggingInterceptor(
          msg -> {
            if (log.isDebugEnabled()) {
              log.debug(msg);
            }
          });
  loggingInterceptor.setLevel(Level.BASIC);

  OkHttpClient.Builder client =
      new OkHttpClient()
          .newBuilder()
          .sslSocketFactory(socketFactory, (X509TrustManager) trustManagers[0])
          .connectionSpecs(singletonList(ConnectionSpec.MODERN_TLS))
          .followSslRedirects(false)
          .retryOnConnectionFailure(true)
          .connectTimeout(keywhiz.getClientTimeout(), SECONDS)
          .readTimeout(keywhiz.getClientTimeout(), SECONDS)
          .writeTimeout(keywhiz.getClientTimeout(), SECONDS)
          .addInterceptor(
              chain -> {
                Request req =
                    chain
                        .request()
                        .newBuilder()
                        .addHeader(CONTENT_TYPE, JSON.toString())
                        .addHeader(USER_AGENT, "OneOps-Secrets-Proxy")
                        .build();
                return chain.proceed(req);
              })
          .addInterceptor(loggingInterceptor);

  if (!isClientAuthEnabled()) {
    log.info("Client auth is disabled. Configuring the cookie manager and XSRF interceptor.");
    cookieMgr = new CookieManager();
    cookieMgr.setCookiePolicy(ACCEPT_ALL);
    client
        .cookieJar(new JavaNetCookieJar(cookieMgr))
        .addNetworkInterceptor(new XsrfTokenInterceptor());
  }
  return client.build();
}
 
Example 10
Source File: RundeckClient.java    From rundeck-cli with Apache License 2.0 4 votes vote down vote up
private static void buildFormAuth(
        final String baseUrl,
        final String username,
        final String password, final OkHttpClient.Builder builder
)
{
    HttpUrl parse = HttpUrl.parse(baseUrl);
    validateBaseUrl(baseUrl, parse);
    validateNotempty(username, "User cannot be blank or null");
    validateNotempty(password, "Password cannot be blank or null");

    String appBaseUrl = buildBaseAppUrlForVersion(baseUrl);

    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    builder.cookieJar(new JavaNetCookieJar(cookieManager));


    String postUrl = parse
            .newBuilder()
            .addPathSegment(
                    System.getProperty(
                            "rundeck.client.j_security_check",
                            "j_security_check"
                    ))
            .build()
            .toString();

    builder.addInterceptor(new FormAuthInterceptor(
            username,
            password,
            appBaseUrl,
            postUrl,
            System.getProperty(
                    "rundeck.client.j_username",
                    "j_username"
            ),
            System.getProperty(
                    "rundeck.client.j_password",
                    "j_password"
            ),
            System.getProperty(
                    "rundeck.client.user.error",
                    "/user/error"
            )

    ));

}
 
Example 11
Source File: HttpClient.java    From StubbornJava with MIT License 4 votes vote down vote up
public static OkHttpClient newClientWithCookieJar() {
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
    return client.newBuilder().cookieJar(cookieJar).build();
}
 
Example 12
Source File: OkHttpUtil.java    From Pas with Apache License 2.0 4 votes vote down vote up
public static void setCookie(CookieManager cookieManager) {
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    getInstance().mOkHttpClient.setCookieHandler(cookieManager);
}
 
Example 13
Source File: OkHttpUtil.java    From Pas with Apache License 2.0 4 votes vote down vote up
public static void setCookie(CookieManager cookieManager) {
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    getInstance().mOkHttpClient.setCookieHandler(cookieManager);
}
 
Example 14
Source File: DOkHttp.java    From Pas with Apache License 2.0 4 votes vote down vote up
public static void setCookie(CookieManager cookieManager) {
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    getInstance().mOkHttpClient.setCookieHandler(cookieManager);
}
 
Example 15
Source File: SHelper.java    From JumpGo with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * @see "http://blogs.sun.com/CoreJavaTechTips/entry/cookie_handling_in_java_se"
 */
public static void enableCookieMgmt() {
    CookieManager manager = new CookieManager();
    manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);
}