Example usage for java.net CookieHandler setDefault

List of usage examples for java.net CookieHandler setDefault

Introduction

In this page you can find the example usage for java.net CookieHandler setDefault.

Prototype

public static synchronized void setDefault(CookieHandler cHandler) 

Source Link

Document

Sets (or unsets) the system-wide cookie handler.

Usage

From source file:remdo.services.NotificationService.java

@Override
public void onCreate() {
    //Toast.makeText(this, "NotificationService.onCreate()", Toast.LENGTH_LONG).show();

    //Establecemos el administrador de cookies por defecto
    ProjectApplication applicationContext = ((ProjectApplication) getApplicationContext());
    CookieManager cookieManager = applicationContext.getCookieManager();
    CookieHandler.setDefault(cookieManager);

    //Obtenemos las preferencias compartidas
    SharedPreferences preferencesLogin = getSharedPreferences("login", MODE_PRIVATE);
    //mHost = preferencesLogin.getString("host", null);

    dm = new DatabaseHelper(applicationContext);
    mHost = dm.getDevicebyDevType(1, 0).url;
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

/**
 * no-arg constructor for OkHttp client/*from  w w  w .  ja va 2 s  . c  om*/
 */
public TankOkHttpClient() {
    try {

        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        } };

        // Setup SSL to accept all certs
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, null);
        sslSocketFactory = sslContext.getSocketFactory();

        // Setup Cookie manager
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);
        okHttpClient.setCookieHandler(cookieManager);

        okHttpClient.setConnectTimeout(30000, TimeUnit.MILLISECONDS);
        okHttpClient.setReadTimeout(30000, TimeUnit.MILLISECONDS); // Socket-timeout
        okHttpClient.setFollowRedirects(true);
        okHttpClient.setFollowSslRedirects(true);

        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

@Override
public void onCreate() {
    super.onCreate();

    preferences = getSharedPreferences(Dashboard.SHARED_PREFERENCES, MODE_PRIVATE);
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
}

From source file:org.kegbot.api.KegbotApiImpl.java

public KegbotApiImpl(AppConfiguration config, String userAgent) {
    mConfig = config;// w  w  w  .java2 s  . co  m
    mCookieManager = new CookieManager();
    mClient = new OkHttpClient();
    mClient.setCookieHandler(mCookieManager);
    CookieHandler.setDefault(mCookieManager);
    mUserAgent = userAgent;
}

From source file:edu.stanford.epadd.launcher.Main.java

private static boolean isURLAlive(String url) throws IOException {
    try {/*from  ww w.jav a  2s  .c om*/
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false

        // since "index" may auto load default archive, attach it to session, and redirect to "info" page,
        // we need to maintain the session across the pages.
        // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

        HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:edgeserver.Publicador.java

private String testServer() throws Exception {
    // make sure cookies is turn on
    CookieHandler.setDefault(new CookieManager());

    HTTPClient http = new HTTPClient();

    List<NameValuePair> GatewayParams = new ArrayList<>();

    String result = http.GetPageContent(this.urlInsertDado, GatewayParams);

    return result;
}

From source file:net.sf.jabref.importer.fetcher.IEEEXploreFetcher.java

public IEEEXploreFetcher(JournalAbbreviationLoader abbreviationLoader) {
    super();//w w w.  j  a va  2s.  c  o m
    this.abbreviationLoader = Objects.requireNonNull(abbreviationLoader);
    CookieHandler.setDefault(new CookieManager());
}

From source file:org.apache.jsp.communities_jsp.java

public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) {
      if (localCookie)
          CookieHandler.setDefault(cm);

      try {//from w w  w.  j a v a 2  s. c  o m
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          URL url = new URL(API_ROOT + addr);
          URLConnection urlConnection = url.openConnection();
          String cookieVal = getBrowserInfiniteCookie(request);
          if (cookieVal != null) {
              urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
              urlConnection.setDoInput(true);
              urlConnection.setDoOutput(true);
              urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
          }
          IOUtils.copy(urlConnection.getInputStream(), output);
          String newCookie = getConnectionInfiniteCookie(urlConnection);
          if (newCookie != null && response != null) {
              setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
          }
          return output.toString();
      } catch (IOException e) {
          System.out.println(e.getMessage());
          return null;
      }
  }

From source file:org.apache.jsp.sources_jsp.java

public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) {
       if (localCookie)
           CookieHandler.setDefault(cm);

       try {/*from   w w  w .j  av a 2 s .c om*/
           ByteArrayOutputStream output = new ByteArrayOutputStream();
           URL url = new URL(API_ROOT + addr);
           URLConnection urlConnection = url.openConnection();
           String cookieVal = getBrowserInfiniteCookie(request);
           if (cookieVal != null) {
               urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
               urlConnection.setDoInput(true);
               urlConnection.setDoOutput(true);
               urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
           }
           IOUtils.copy(urlConnection.getInputStream(), output);
           String newCookie = getConnectionInfiniteCookie(urlConnection);
           if (newCookie != null && response != null) {
               setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
           }
           return output.toString();
       } catch (IOException e) {
           System.out.println(e.getMessage());
           return null;
       }
   }

From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java

public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData)
        throws Throwable {
    HttpURLConnection connection = null;
    InputStream is = null;/*w ww .  j  av  a  2  s. c o m*/
    int statusCode;

    if (DUMP_PAYLOAD) {
        log.debug("Send request to {}", remoteServiceURL);
        log.debug("Request payload: {}", requestData);
    }

    // Send request
    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    try {
        CookieHandler.setDefault(cookieManager);

        URL url = new URL(remoteServiceURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName);
        connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL);
        connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8");
        connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length);

        CookieStore store = cookieManager.getCookieStore();
        String cookiesStr = "";

        for (HttpCookie cookie : store.getCookies()) {
            if (!"".equals(cookiesStr))
                cookiesStr += "; ";
            cookiesStr += cookie.getName() + "=" + cookie.getValue();
        }

        connection.setRequestProperty("Cookie", cookiesStr);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(requestData);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationException("IOException while sending RPC request", e);
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
    }

    // Receive and process response
    try {

        is = connection.getInputStream();
        statusCode = connection.getResponseCode();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        String encodedResponse = baos.toString("UTF8");
        if (DUMP_PAYLOAD) {
            log.debug("Response code: {}", statusCode);
            log.debug("Response payload: {}", encodedResponse);
        }

        // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse);
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new StatusCodeException(statusCode, encodedResponse);
        } else if (encodedResponse == null) {
            // This can happen if the XHR is interrupted by the server dying
            throw new InvocationException("No response payload");
        } else if (isReturnValue(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            return responseReader.read(createStreamReader(encodedResponse));
        } else if (isThrownException(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject();
            throw throwable;
        } else {
            throw new InvocationException("Unknown response " + encodedResponse);
        }
    } catch (IOException e) {

        log.error("error response: {}", IOUtils.toString(connection.getErrorStream()));
        throw new InvocationException("IOException while receiving RPC response", e);

    } catch (SerializationException e) {
        throw new InvocationException("Error while deserialization response", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (connection != null) {
            // connection.disconnect();
        }
    }
}