簡體   English   中英

來自Appengine的GetCoockie

[英]GetCoockie from appengine

嘿,我已經在App Engine中編寫了服務器。 到目前為止,我已經使用HttpDefaultClient了。

 protected Boolean doInBackground(String... tokens) {

        try {

            // Don't follow redirects
            params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

            HttpGet httpGet = new HttpGet("http://" + appId
                    + ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);

            response = httpclient.execute(httpGet);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();

            if(response.getStatusLine().getStatusCode() != 302){
                // Response should be a redirect
                return false;
            }

            //check if we received the ACSID or the SACSID cookie, depends on http or https request
            for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
                if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
                    return true;
                }
            }

        }  catch (Exception e) {
            e.printStackTrace();
            cancel(true);
        } finally {
            params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        }
        return false;
    }

有誰知道我如何通過其他連接獲得相同的小鳥?

我知道如何通過httpUrlconnection接收令牌:

     private String getAuthToken() {

            AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(
                    mAccount, "ah", null, true, null, null);
            Bundle bundle;
            try {
                bundle = future.getResult(10, TimeUnit.SECONDS);
            } catch (OperationCanceledException | IOException | AuthenticatorException e) {
                Log.e(TAG, "Unexpected error while getting an auth token: ", e);
                throw new RuntimeException(e);
            }

            return bundle.getString(AccountManager.KEY_AUTHTOKEN);
        }

:
    private URL getAuthUrl(String token) {
        api = "http://" + appId+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + token;
        String path = Uri.parse(mBaseUrl)
                .buildUpon()
                .appendEncodedPath("_ah/login")
                .appendQueryParameter("continue", mBaseUrl)
                .appendQueryParameter("auth", token)
                .build()
                .toString();

        try {
            return new URL(api);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
private String getAuthCookie(URL authUrl) {
        HttpURLConnection conn = ((HttpURLConnection) authUrl.openConnection());
        String cookie = conn.getHeaderField("Set-Cookie"); // returns null!
        return cookie;

}

知道為什么嗎? 以及如何解決?

我收到了:NID = 72 = bIkTJcJ1o1iX988WeqjEhAELifvxtDOoD0sIe-VqZQK0ToezFvDSx0ctjko8KZyJYA7S1aAyl-7WYh6Wue-UHhSJYgXSQg9NrFXEMBI; expires =星期四,2016年4月7日22:56:30 GMT; 路徑= /; domain = .google.com; HttpOnly

答:

 package com.example.daniel.testing9;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * AppEngine authentication with a Google account works as follows:
 1. First we obtain a token from the Google account on device.
 2. We authenticate with Appengine at /_ah/login URL
 3. If authentication is successful, an ACSID (SACSID for https) cookie is set
 4. If the token has expired (default 24 hours), then we invalidate it and try again.
 5. Set the [S]ACSID cookie on future requests, e.g.:
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 conn.setRequestProperty("Cookie", cookie);
 */
public class AuthHelper {
    private static final String TAG = "auth";
    public static boolean finished = false;
    private final AccountManager mAccountManager;
    private final Account mAccount;
    private final String mBaseUrl;
    private static String _cookie = null;
    String appId;
    String api;
    String token;
    static AuthHelper instance = null;
    public static AuthHelper getInstance() {
        if (instance == null) {
            AccountManager accountManager = AccountManager.get(MainActivity.context.getApplicationContext());
            accountManager = AccountManager.get(MainActivity.context.getApplicationContext());

            // assembling all gmail accounts
            Account[] accounts = accountManager.getAccountsByType("com.google");

            // add all gmail accounts :
            ArrayList<String> accountList = new ArrayList<String>();
            for (Account account : accounts) {
                accountList.add(account.name);
            }

            Account account = accounts[0];
            instance = new AuthHelper(accountManager, account, Constants.SERVER_REQUESTS.MY_APP_WEBSITE,
                    Constants.SERVER_REQUESTS.MY_APP_ID);
        }
        return instance;
    }
    public AuthHelper(@NonNull AccountManager accountManager,
                            @NonNull Account account,
                            @NonNull String appspotBaseUrl, String appid) {
        mAccountManager = accountManager;
        mAccount = account;
        mBaseUrl = appspotBaseUrl;
        this.appId = appid;
    }


    public String getAuthPath(String url) {
        if (token == null) {
            token = getAuthToken();
        }
       return  api = Constants.SERVER_REQUESTS.MY_APP_WEBSITE+"_ah/login?continue="+url+"&auth=" + token;
    }
    public String authenticateAndGetCookie() {
        for (int i = 0; i < 2; i++) {
            token = getAuthToken();
            URL authUrl = getAuthUrl(token);
            String cookie = getAuthCookie(authUrl);
            if (cookie != null) {
                _cookie = cookie;
                return cookie;
            }
            invalidateAuthToken(token);
        }

        return null;
    }
    private String getAuthCookie(URL authUrl) {
        try {
            HttpURLConnection conn = ((HttpURLConnection) authUrl.openConnection());
            return conn.getHeaderField("Set-Cookie");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private URL getAuthUrl(String token) {
        api = "http://" + appId+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + token;
        String path = Uri.parse(mBaseUrl)
                .buildUpon()
                .appendEncodedPath("_ah/login")
              //  .appendQueryParameter("continue", mBaseUrl)
                .appendQueryParameter("auth", token)
                .build()
                .toString();

        try {
            return new URL(path);
            //return new URL(api);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    private String getAuthToken() {

        AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(
                mAccount, "ah", null, true, null, null);
        Bundle bundle;
        try {
            bundle = future.getResult(10, TimeUnit.SECONDS);
        } catch (OperationCanceledException | IOException | AuthenticatorException e) {
            Log.e(TAG, "Unexpected error while getting an auth token: ", e);
            throw new RuntimeException(e);
        }

        return bundle.getString(AccountManager.KEY_AUTHTOKEN);
    }

    private void invalidateAuthToken(String token) {
        mAccountManager.invalidateAuthToken(mAccount.type, token);
        finished = true;
    }


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM