Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/211.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将android应用程序连接到应用程序引擎_Android_Google App Engine_Cookies_Connection - Fatal编程技术网

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

如何将android应用程序连接到应用程序引擎,android,google-app-engine,cookies,connection,Android,Google App Engine,Cookies,Connection,我正在尝试将我的Android应用程序连接到我在appengine上打开的服务器 我的服务器名称是:dddd-daniel-2345 服务器的网站是: 以下是如何在应用程序引擎中从android应用程序连接到服务器: app.yaml: application: dddd-daniel-2345 version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: .* script: main.app

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

我的服务器名称是:dddd-daniel-2345 服务器的网站是:

以下是如何在应用程序引擎中从android应用程序连接到服务器:

app.yaml:

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.py:

#!/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)
我的应用程序代码: 添加到manifast

主要活动:

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

}
package com.ap2.demo.com通信;
导入android.accounts.Account;
导入android.accounts.AccountManager;
导入android.content.Intent;
导入android.support.v7.app.ActionBarActivity;
导入android.os.Bundle;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.Spinner;
导入com.ap2.demo.R;
导入com.ap2.demo.splash活动;
导入org.apache.http.impl.client.DefaultHttpClient;
导入java.util.ArrayList;
公共类MainActivity扩展了ActionBarActivity{
会计经理会计经理;
私人账户[]账户;
纺纱机;
DefaultHttpClient httpClient=新的DefaultHttpClient();
账户;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accountManager=accountManager.get(getApplicationContext());
//收集所有gmail帐户
accounts=accountManager.getAccountsByType(“com.google”);
//添加所有gmail帐户:
ArrayList accountList=新的ArrayList();
用于(账户:账户){
accountList.add(account.name);
}
//设置要查看的微调器
微调器=(微调器)findViewById(R.id.account);
ArrayAdapter dataAdapter=新的ArrayAdapter(此,
android.R.layout.simple\u微调器\u项目,accountList);
dataAdapter.setDropDownViewResource(android.R.layout.simple\u微调器\u下拉项);
spinner.setAdapter(dataAdapter);
按钮startAuth=(按钮)findViewById(R.id.startAuth);
startAuth.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
微调器=(微调器)findViewById(R.id.account);
account=accounts[spinner.getSelectedItemPosition()];
accountManager.getAuthToken(帐户,“啊”,null,false,
已获取新的(httpClient,MainActivity.this),空;
意向意向=新意向(MainActivity.this、SplashActivity.class);
星触觉(意向);
}
});
}
受保护的void onActivityResult(int请求代码、int结果代码、意图数据)
{
if(resultCode==RESULT\u OK){
accountManager.getAuthToken(帐户,“啊”,null,false,
已获取新的(httpClient,MainActivity.this),空;
}
else if(resultCode==RESULT\u取消){
//用户取消
}
}
}
已收购的Ontoken:

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.com通信;
导入android.accounts.AccountManager;
导入android.accounts.AccountManagerCallback;
导入android.accounts.accountmanager未来;
导入android.app.Activity;
导入android.content.Intent;
导入android.os.Bundle;
导入org.apache.http.impl.client.DefaultHttpClient;
/**
*丹尼尔于2015年6月19日创作。
*/
/*身份验证令牌请求的结果将返回到应用程序
通过发出请求时指定的帐户管理器回调。
如果针对AccountManager.KEY\u Intent键存储了意图,请检查返回的捆绑包。
如果有意图,则使用该意图启动活动以请求用户权限
否则,您可以从bundle中检索auth令牌*/
实现AccountManagerCallback的公共类{
私有静态最终int用户_权限=989;
专用静态最终字符串APP_ID=“dddd-daniel-2345”;
//专用静态最终字符串APP_ID=“dddd-daniel-1234”;
私有默认httpclient httpclient;
活动;
已获取公共资源(DefaultHttpClient httpclient,活动)
{
this.httpclient=httpclient;
这个。活动=活动;
}
@凌驾
公共作废运行(AccountManagerFuture结果){
束;
试一试{
bundle=(bundle)result.getResult();
if(bundle.containsKey(AccountManager.KEY_INTENT)){
Intent Intent=bundle.getParcelable(AccountManager.KEY\u Intent);
setFlags(intent.getFlags()&~intent.FLAG\u活动\u新任务);
activity.startActivityForResult(意图、用户权限);
}否则{
setAuthToken(bundle);
}
}
捕获(例外e){
e、 printStackTrace();
}
}
//使用身份验证令牌并请求身份验证cookie
受保护的void setAuthToken(捆绑包){
String authToken=bundle.getString(AccountManager.KEY\u authToken);
新的GetCookie(httpclient,APP_ID,activity.getBaseContext()).execute(authToken);
}
}
GetCookie:

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);
    }
}
package com.ap2.demo.com通信;
导入android.content.Context;
导入android.os.AsyncTask;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.params.ClientPNames;
导入org.apache.http.cookie.cookie;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.params.HttpParams;
导入java.io.ByteArrayOutputStream;
/**
*丹尼尔于2015年6月19日创作。
*/
公共类GetCookie扩展异步任务{
字符串appId;
HttpParams-params;
私有HttpResponse响应;
//私有静态最终字符串链接\u到\u获取\u身份验证=”http://dddd-daniel-2345.appspot.com/";
私有静态最终字符串链接\u到\u获取\u身份验证=”http://dddd-daniel-2345.appspot.com/";
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();
    }
}
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginBottom="10dp"
        android:text="@string/choose_account"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <Spinner android:id="@+id/account"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1" />

    <Button
        android:id="@+id/startAuth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/account"
        android:layout_marginTop="10dp"
        android:text="@string/send_button" />

</RelativeLayout>