Example usage for java.net HttpCookie HttpCookie

List of usage examples for java.net HttpCookie HttpCookie

Introduction

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

Prototype

public HttpCookie(String name, String value) 

Source Link

Document

Constructs a cookie with a specified name and value.

Usage

From source file:self.philbrown.droidQuery.Ajax.java

protected TaskResponse doInBackground(Void... arg0) {
    if (this.isCancelled)
        return null;

    //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming.
    if (!beforeSendIsAsync) {
        try {//from   w w w . j ava2  s  . c  o  m
            mutex.acquire();
        } catch (InterruptedException e) {
            Log.w("AjaxTask", "Synchronization Error. Running Task Async");
        }
        final Thread asyncThread = Thread.currentThread();
        isLocked = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (options.beforeSend() != null) {
                    if (options.context() != null)
                        options.beforeSend().invoke($.with(options.context()), options);
                    else
                        options.beforeSend().invoke(null, options);
                }

                if (options.isAborted()) {
                    cancel(true);
                    return;
                }

                if (options.global()) {
                    synchronized (globalTasks) {
                        if (globalTasks.isEmpty()) {
                            $.ajaxStart();
                        }
                        globalTasks.add(Ajax.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(Ajax.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

    //handle cached responses
    Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options);
    //handle ajax caching option
    if (cachedResponse != null && options.cache()) {
        Success s = new Success(cachedResponse);
        s.reason = "cached response";
        s.allHeaders = null;
        return s;

    }

    if (connection == null) {
        try {
            String type = options.type();
            URL url = new URL(options.url());
            if (type == null) {
                type = "GET";
            }
            if (type.equalsIgnoreCase("CUSTOM")) {

                try {
                    connection = options.customConnection();
                } catch (Exception e) {
                    connection = null;
                }

                if (connection == null) {
                    Log.w("droidQuery.ajax",
                            "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                }
            } else {
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod(type);
                if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) {
                    connection.setDoOutput(true);
                }
            }
        } catch (Throwable t) {
            if (options.debug())
                t.printStackTrace();
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = 0;
            e.reason = "Bad Configuration";
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = new Headers();
            e.error = error;
            return e;
        }

    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", null);
    args.put("connection", connection);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            OutputStream os = connection.getOutputStream();
            os.write(options.data().toString().getBytes());
            os.close();
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    if (options.timeout() != 0) {
        connection.setConnectTimeout(options.timeout());
        connection.setReadTimeout(options.timeout());
    }

    if (options.trustedCertificate() != null) {

        Certificate ca = options.trustedCertificate();

        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = null;
        try {
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
        } catch (KeyStoreException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (CertificateException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (IOException e) {
            if (options.debug())
                e.printStackTrace();
        }

        if (keyStore == null) {
            Log.w("Ajax", "Could not configure trusted certificate");
        } else {
            try {
                //Create a TrustManager that trusts the CAs in our KeyStore
                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                tmf.init(keyStore);

                //Create an SSLContext that uses our TrustManager
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, tmf.getTrustManagers(), null);
                ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
            } catch (KeyManagementException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (KeyStoreException e) {
                if (options.debug())
                    e.printStackTrace();
            }
        }
    }

    try {

        if (options.cookies() != null) {
            CookieManager cm = new CookieManager();
            CookieStore cookies = cm.getCookieStore();
            URI uri = URI.create(options.url());
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue());
                cookies.add(uri, cookie);
            }
            connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies()));
        }

        connection.connect();
        final int statusCode = connection.getResponseCode();
        final String message = connection.getResponseMessage();

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke($.with(options.context()), connection, options.dataType());
            else
                options.dataFilter().invoke(null, connection, options.dataType());
        }

        final Function function = options.statusCode().get(statusCode);
        if (function != null) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (options.context() != null)
                        function.invoke($.with(options.context()), statusCode, options.clone());
                    else
                        function.invoke(null, statusCode, options.clone());
                }

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        InputStream stream = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseText(stream);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing xml");
                if (options.customXMLParser() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    if (options.SAXContentHandler() != null)
                        options.customXMLParser().parse(stream, options.SAXContentHandler());
                    else
                        options.customXMLParser().parse(stream, new DefaultHandler());
                    parsedResponse = "Response handled by custom SAX parser";
                } else if (options.SAXContentHandler() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    factory.setFeature("http://xml.org/sax/features/namespaces", false);
                    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                    SAXParser parser = factory.newSAXParser();

                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(options.SAXContentHandler());
                    reader.parse(new InputSource(stream));
                    parsedResponse = "Response handled by custom SAX content handler";
                } else {
                    parsedResponse = parseXML(connection);
                }
            } else if (dataType.equalsIgnoreCase("json")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(connection);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(connection);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseImage(stream);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(connection);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } finally {
            connection.disconnect();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
            }
        }

        if (statusCode >= 300) {
            //an error occurred
            Error e = new Error(parsedResponse);
            Log.e("Ajax Test", parsedResponse.toString());
            //AjaxError error = new AjaxError();
            //error.request = request;
            //error.options = options;
            e.status = e.status;
            e.reason = e.reason;
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //handle ajax ifModified option
            List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified");
            if (lastModifiedHeaders.size() >= 1) {
                try {
                    String h = lastModifiedHeaders.get(0);
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
                    Date lastModified = format.parse(h);
                    if (options.ifModified() && lastModified != null) {
                        Date lastModifiedDate;
                        synchronized (lastModifiedUrls) {
                            lastModifiedDate = lastModifiedUrls.get(options.url());
                        }

                        if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) {
                            //request response has not been modified. 
                            //Causes an error instead of a success.
                            Error e = new Error(parsedResponse);
                            AjaxError error = new AjaxError();
                            error.connection = connection;
                            error.options = options;
                            e.status = e.status;
                            e.reason = e.reason;
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
                            e.error = error;
                            Function func = options.statusCode().get(304);
                            if (func != null) {
                                if (options.context() != null)
                                    func.invoke($.with(options.context()));
                                else
                                    func.invoke(null);
                            }
                            return e;
                        } else {
                            synchronized (lastModifiedUrls) {
                                lastModifiedUrls.put(options.url(), lastModified);
                            }
                        }
                    }
                } catch (Throwable t) {
                    Log.e("Ajax", "Could not parse Last-Modified Header", t);
                }

            }

            //Now handle a successful request

            Success s = new Success(parsedResponse);
            s.reason = message;
            s.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            error.response = e.response;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (connection != null)
                e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            else
                e.allHeaders = new Headers();
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java

@Override
public synchronized InstanceList getInstances() {
    if (checkLogin()) {
        try {/*from w  ww .j a va 2  s  . co m*/
            startHttpClient();

            Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_INSTANCES)
                    .method(HttpMethod.GET).header(HttpHeader.ACCEPT, "application/json")
                    .header(HttpHeader.CONTENT_TYPE, "application/json")
                    .cookie(new HttpCookie("ZWAYSession", mZWaySessionId));

            if (mUseRemoteService) {
                request.cookie(new HttpCookie("ZBW_SESSID", mZWayRemoteSessionId));
            }

            ContentResponse response = request.send();

            // Check HTTP status code
            int statusCode = response.getStatus();
            if (statusCode != HttpStatus.OK_200) {
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getInstances();
                    }
                } else {
                    processResponseStatus(statusCode);
                }
            } else {
                return parseGetInstances(response.getContentAsString());
            }
        } catch (Exception e) {
            if (e.getCause() instanceof HttpResponseException) {
                int statusCode = ((HttpResponseException) e.getCause()).getResponse().getStatus();
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getInstances();
                    }
                }
            } else {
                handleException(e, "get instances");
            }
        } finally {
            stopHttpClient();
        }
    } // no else ... checkLogin() method will invoke the appropriate callback method

    return null;
}

From source file:org.parosproxy.paros.network.HttpRequestHeader.java

/**
 * Gets a list of the http cookies from this request Header.
 *
 * @return the http cookies//  ww w . j  a v  a2 s  .co m
 * @throws IllegalArgumentException if a problem is encountered while
 * processing the "Cookie: " header line.
 */
public List<HttpCookie> getHttpCookies() {
    List<HttpCookie> cookies = new LinkedList<>();
    // Use getCookieParams to reduce the places we parse cookies
    TreeSet<HtmlParameter> ts = getCookieParams();
    Iterator<HtmlParameter> it = ts.iterator();
    while (it.hasNext()) {
        HtmlParameter htmlParameter = it.next();
        if (!htmlParameter.getName().isEmpty()) {
            try {
                cookies.add(new HttpCookie(htmlParameter.getName(), htmlParameter.getValue()));

            } catch (IllegalArgumentException e) {
                // Occurs while scanning ;)
                log.debug(e.getMessage() + " " + htmlParameter.getName());
            }
        }
    }

    return cookies;
}

From source file:com.novartis.opensource.yada.YADAQuery.java

/**
 * Adds the cookie with {@code name} to the {@link #cookies} List
 * @param name the name of the cookie./* w ww  . j a  v a2  s .c o  m*/
 * @param val the value of the cookie with {@code name}
 * @since 5.1.0
 */
public void addCookie(String name, String val) {
    HttpCookie cookie = new HttpCookie(name, val);
    addCookie(cookie);
}

From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java

@Override
public void getInstances(final IZWayCallback<InstanceList> callback) {
    if (checkLogin()) {
        try {/*from  w  w w  . j ava2 s .c o  m*/
            startHttpClient();

            Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_INSTANCES)
                    .method(HttpMethod.GET).header(HttpHeader.ACCEPT, "application/json")
                    .header(HttpHeader.CONTENT_TYPE, "application/json")
                    .cookie(new HttpCookie("ZWAYSession", mZWaySessionId))
                    .onRequestFailure(new ZWayFailureListener());

            if (mUseRemoteService) {
                request.cookie(new HttpCookie("ZBW_SESSID", mZWayRemoteSessionId));
            }

            request.send(new BufferingResponseListener() {
                @Override
                public void onComplete(Result result) {
                    int statusCode = result.getResponse().getStatus();
                    if (statusCode != HttpStatus.OK_200) {
                        if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                            if (getLogin() == null) {
                                mCaller.authenticationError();
                            } else {
                                getInstances(callback);
                            }
                        } else {
                            processResponseStatus(statusCode);
                        }
                    } else {
                        callback.onSuccess(parseGetInstances(getContentAsString()));
                    }
                }
            });
        } catch (Exception e) {
            if (e.getCause() instanceof HttpResponseException) {
                int statusCode = ((HttpResponseException) e.getCause()).getResponse().getStatus();
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        getInstances(callback);
                    }
                }
            } else {
                handleException(e, "get instances");
            }
        } finally {
            // do not stop http client for asynchronous call
        }
    } // no else ... checkLogin() method will invoke the appropriate callback method
}

From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java

@Override
public synchronized LocationList getLocations() {
    if (checkLogin()) {
        try {//  w  w  w  .ja  v a 2s .  co m
            startHttpClient();

            Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_LOCATIONS)
                    .method(HttpMethod.GET).header(HttpHeader.ACCEPT, "application/json")
                    .header(HttpHeader.CONTENT_TYPE, "application/json")
                    .cookie(new HttpCookie("ZWAYSession", mZWaySessionId));

            if (mUseRemoteService) {
                request.cookie(new HttpCookie("ZBW_SESSID", mZWayRemoteSessionId));
            }

            ContentResponse response = request.send();

            // Check HTTP status code
            int statusCode = response.getStatus();
            if (statusCode != HttpStatus.OK_200) {
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getLocations();
                    }
                } else {
                    processResponseStatus(statusCode);
                }
            } else {
                return parseGetLocations(response.getContentAsString());
            }
        } catch (Exception e) {
            if (e.getCause() instanceof HttpResponseException) {
                int statusCode = ((HttpResponseException) e.getCause()).getResponse().getStatus();
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getLocations();
                    }
                }
            } else {
                handleException(e, "get locations");
            }
        } finally {
            stopHttpClient();
        }
    } // no else ... checkLogin() method will invoke the appropriate callback method

    return null;
}

From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java

@Override
public void getLocations(final IZWayCallback<LocationList> callback) {
    if (checkLogin()) {
        try {/*from  w ww.  j av  a 2  s .  co m*/
            startHttpClient();

            Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_INSTANCES)
                    .method(HttpMethod.GET).header(HttpHeader.ACCEPT, "application/json")
                    .header(HttpHeader.CONTENT_TYPE, "application/json")
                    .cookie(new HttpCookie("ZWAYSession", mZWaySessionId))
                    .onRequestFailure(new ZWayFailureListener());

            if (mUseRemoteService) {
                request.cookie(new HttpCookie("ZBW_SESSID", mZWayRemoteSessionId));
            }

            request.send(new BufferingResponseListener() {
                @Override
                public void onComplete(Result result) {
                    int statusCode = result.getResponse().getStatus();
                    if (statusCode != HttpStatus.OK_200) {
                        if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                            if (getLogin() == null) {
                                mCaller.authenticationError();
                            } else {
                                getLocations(callback);
                            }
                        } else {
                            processResponseStatus(statusCode);
                        }
                    } else {
                        callback.onSuccess(parseGetLocations(getContentAsString()));
                    }
                }
            });
        } catch (Exception e) {
            if (e.getCause() instanceof HttpResponseException) {
                int statusCode = ((HttpResponseException) e.getCause()).getResponse().getStatus();
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        getLocations(callback);
                    }
                }
            } else {
                handleException(e, "get locations");
            }
        } finally {
            // do not stop http client for asynchronous call
        }
    } // no else ... checkLogin() method will invoke the appropriate callback method
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

private void exhangeToken() throws IOException, URISyntaxException {

    this.renewTime = 0;
    String cookiesJson = "{\"cookies\":{\"." + getAmazonSite() + "\":[]}}";
    String cookiesBase64 = Base64.getEncoder().encodeToString(cookiesJson.getBytes());

    String exchangePostData = "di.os.name=iOS&app_version=2.2.223830.0&domain=." + getAmazonSite()
            + "&source_token=" + URLEncoder.encode(this.refreshToken, "UTF8")
            + "&requested_token_type=auth_cookies&source_token_type=refresh_token&di.hw.version=iPhone&di.sdk.version=6.10.0&cookies="
            + cookiesBase64 + "&app_name=Amazon%20Alexa&di.os.version=11.4.1";

    HashMap<String, String> exchangeTokenHeader = new HashMap<String, String>();
    exchangeTokenHeader.put("Cookie", "");

    String exchangeTokenJson = makeRequestAndReturnString("POST",
            "https://www." + getAmazonSite() + "/ap/exchangetoken", exchangePostData, false,
            exchangeTokenHeader);//from  ww w .j a va  2s  .  com
    JsonExchangeTokenResponse exchangeTokenResponse = gson.fromJson(exchangeTokenJson,
            JsonExchangeTokenResponse.class);

    org.openhab.binding.amazonechocontrol.internal.jsons.JsonExchangeTokenResponse.Response response = exchangeTokenResponse.response;
    if (response != null) {
        org.openhab.binding.amazonechocontrol.internal.jsons.JsonExchangeTokenResponse.Tokens tokens = response.tokens;
        if (tokens != null) {
            @Nullable
            Map<String, Cookie[]> cookiesMap = tokens.cookies;
            if (cookiesMap != null) {
                for (String domain : cookiesMap.keySet()) {
                    Cookie[] cookies = cookiesMap.get(domain);
                    for (Cookie cookie : cookies) {
                        if (cookie != null) {
                            HttpCookie httpCookie = new HttpCookie(cookie.Name, cookie.Value);
                            httpCookie.setPath(cookie.Path);
                            httpCookie.setDomain(domain);
                            Boolean secure = cookie.Secure;
                            if (secure != null) {
                                httpCookie.setSecure(secure);
                            }
                            this.cookieManager.getCookieStore().add(null, httpCookie);
                        }
                    }
                }
            }
        }
    }
    if (!verifyLogin()) {
        throw new ConnectionException("Verify login failed after token exchange");
    }
    this.renewTime = (long) (System.currentTimeMillis() + Connection.expiresIn * 1000d / 0.8d); // start renew at
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public String getLoginPage() throws IOException, URISyntaxException {
    // clear session data
    logout();//from w ww . j a  va 2s  .  com

    logger.debug("Start Login to {}", alexaServer);

    String mapMdJson = "{\"device_user_dictionary\":[],\"device_registration_data\":{\"software_version\":\"1\"},\"app_identifier\":{\"app_version\":\"2.2.223830\",\"bundle_id\":\"com.amazon.echo\"}}";
    String mapMdCookie = Base64.getEncoder().encodeToString(mapMdJson.getBytes());

    cookieManager.getCookieStore().add(new URI("https://www.amazon.com"),
            new HttpCookie("map-md", mapMdCookie));
    cookieManager.getCookieStore().add(new URI("https://www.amazon.com"), new HttpCookie("frc", frc));

    String loginFormHtml = makeRequestAndReturnString("https://www.amazon.com"
            + "/ap/signin?openid.return_to=https://www.amazon.com/ap/maplanding&openid.assoc_handle=amzn_dp_project_dee_ios&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&pageId=amzn_dp_project_dee_ios&accountStatusPolicy=P1&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.mode=checkid_setup&openid.ns.oa2=http://www.amazon.com/ap/ext/oauth/2&openid.oa2.client_id=device:"
            + deviceId
            + "&openid.ns.pape=http://specs.openid.net/extensions/pape/1.0&openid.oa2.response_type=token&openid.ns=http://specs.openid.net/auth/2.0&openid.pape.max_auth_age=0&openid.oa2.scope=device_auth_access");

    logger.debug("Received login form {}", loginFormHtml);
    return loginFormHtml;
}

From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java

@Override
public synchronized DeviceHistoryList getDeviceHistories() {
    if (checkLogin()) {
        try {// ww w .  ja v  a 2  s. com
            startHttpClient();

            Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_DEVICE_HISTORY)
                    .method(HttpMethod.GET).header(HttpHeader.ACCEPT, "application/json")
                    .header(HttpHeader.CONTENT_TYPE, "application/json")
                    .cookie(new HttpCookie("ZWAYSession", mZWaySessionId));

            if (mUseRemoteService) {
                request.cookie(new HttpCookie("ZBW_SESSID", mZWayRemoteSessionId));
            }

            ContentResponse response = request.send();

            // Check HTTP status code
            int statusCode = response.getStatus();
            if (statusCode != HttpStatus.OK_200) {
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getDeviceHistories();
                    }
                } else {
                    processResponseStatus(statusCode);
                }
            } else {
                return parseGetDeviceHistories(response.getContentAsString());
            }
        } catch (Exception e) {
            if (e.getCause() instanceof HttpResponseException) {
                int statusCode = ((HttpResponseException) e.getCause()).getResponse().getStatus();
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getDeviceHistories();
                    }
                }
            } else {
                handleException(e, "get device histories");
            }
        } finally {
            stopHttpClient();
        }
    } // no else ... checkLogin() method will invoke the appropriate callback method

    return null;
}