如何将Android应用程序连接到App引擎

时间:2015-06-20 08:19:09

标签: android google-app-engine cookies connection

我正在尝试将Android中的应用程序连接到我在appengine上打开的服务器。

我的服务器名称是:dddd-daniel-2345 并且服务器的网站是:http://dddd-daniel-2345.appspot.com/

这是如何从Android应用程序连接到app引擎中的服务器:

的app.yaml:

    YourFragment mFragment = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG"); //if you are using support library
     //OR
   YourFragment mFragment = getFragmentManager().findFragmentByTag("Your_Fragment_TAG"); //if you are using support library

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.detach(mFragment);
    ft.attach(mFragment).commit();

main.py:

application: dddd-daniel-2345
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:

- url: .*
  script: main.app

libraries:
- name: webapp2
  version: "2.5.2"

我的应用程序代码: 添加到表现               

Main.Activity:

#!/usr/bin/env python
#
# Copyright 2007 Google Inc.

from google.appengine.api import users
import webapp2


class UserHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ('%s,%s,%s' % (user.email(),user.user_id(),user.nickname()))
        else:
            greeting = ('not logged in')
        self.response.out.write(greeting)

app = webapp2.WSGIApplication([('/', UserHandler),], debug=True)

OnTokenAcquired:

package com.ap2.demo.comunication;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.ap2.demo.R;
import com.ap2.demo.SplashActivity;

import org.apache.http.impl.client.DefaultHttpClient;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {
    AccountManager accountManager;
    private Account[] accounts;
    Spinner spinner;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    Account account;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        accountManager = AccountManager.get(getApplicationContext());

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

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

        // setting spinner to be viewed
        spinner = (Spinner) findViewById(R.id.account);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, accountList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);

        Button startAuth = (Button) findViewById(R.id.startAuth);
        startAuth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spinner = (Spinner) findViewById(R.id.account);
                account = accounts[spinner.getSelectedItemPosition()];

                accountManager.getAuthToken(account, "ah", null, false,
                        new OnTokenAcquired(httpClient, MainActivity.this), null);

                Intent intent = new Intent(MainActivity.this, SplashActivity.class);
                startActivity(intent);
            }
        });

    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == RESULT_OK) {
            accountManager.getAuthToken(account, "ah", null, false,
                    new OnTokenAcquired(httpClient, MainActivity.this), null);
        }
        else if(resultCode ==  RESULT_CANCELED){
            // user canceled
        }
    }

}

的getCookie:

package com.ap2.demo.comunication;

import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Created by Daniel on 19-Jun-15.
 */
/*the result for the auth token request is returned to your application
via the Account Manager Callback you specified when making the request.
check the returned bundle if an Intent is stored against the AccountManager.KEY_INTENT key.
if there is an Intent then start the activity using that intent to ask for user permission
otherwise you can retrieve the auth token from the bundle.*/
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
    private static final int USER_PERMISSION = 989;
    private static final String APP_ID = "dddd-daniel-2345";
   // private static final String APP_ID = "dddd-daniel-1234";
    private DefaultHttpClient httpclient;
    Activity activity;

    public OnTokenAcquired(DefaultHttpClient httpclient, Activity activity)
    {
        this.httpclient = httpclient;
        this.activity   = activity;
    }
    @Override
    public void run(AccountManagerFuture<Bundle> result) {
        Bundle bundle;

        try {
            bundle = (Bundle) result.getResult();
            if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
                intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivityForResult(intent, USER_PERMISSION);

            } else {
                setAuthToken(bundle);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    //using the auth token and ask for a auth cookie
    protected void setAuthToken(Bundle bundle) {
        String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);

        new GetCookie(httpclient, APP_ID, activity.getBaseContext()).execute(authToken);
    }
}

验证

package com.ap2.demo.comunication;

import android.content.Context;
import android.os.AsyncTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

import java.io.ByteArrayOutputStream;

/**
 * Created by Daniel on 19-Jun-15.
 */
public class GetCookie extends AsyncTask<String, Void, Boolean> {
    String appId;
    HttpParams params;
    private HttpResponse response;
   // private static final String LINK_TO_GET_AUTHENTICATED = "http://dddd-daniel-2345.appspot.com/";
    private static final String LINK_TO_GET_AUTHENTICATED = "http://dddd-daniel-2345.appspot.com/";
    //private static final String LINK_TO_GET_AUTHENTICATED = "http://dddd-daniel-1234.appspot.com/";
    Context context;
    private DefaultHttpClient httpclient;

    public GetCookie(DefaultHttpClient httpclient, String appId, Context context)
    {
        this.httpclient = httpclient;
        params = httpclient.getParams();
        this.appId = appId;
        this.context = context;
    }

    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;
    }

    protected void onPostExecute(Boolean result)
    {
        new Auth(httpclient, context).execute(LINK_TO_GET_AUTHENTICATED);
    }
}

activity_main.xml中:

package com.ap2.demo.comunication;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayOutputStream;

/**
 * Created by Daniel on 19-Jun-15.
 */
public class Auth extends AsyncTask<String, Void, Boolean> {

    private DefaultHttpClient httpclient;
    private HttpResponse response;
    private String content =  null;
    Context context;

    public Auth(DefaultHttpClient httpclient, Context context)
    {
        this.httpclient = httpclient;
        this.context = context;
    }

    protected Boolean doInBackground(String... urls) {

        try {

            HttpGet httpGet = new HttpGet(urls[0]);
            response = httpclient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();

            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                content = out.toString();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            cancel(true);
        }
        return false;
    }

    //display the response from the request above
    protected void onPostExecute(Boolean result) {
        Toast.makeText(context, "Response from request: " + content,
                Toast.LENGTH_LONG).show();
    }
}

每当我运行应用程序时,它都会显示正确的Toast。

0 个答案:

没有答案