Search code examples
androidrequestfactory

How does RequestFactory know what Android user is logged in


I have an Android app that successfully uses RequestFactory to manipulate Entities in AppEngine Datastore.

In my AppEngine service, I want to use

UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();

to get information about the current Android user, but getCurrentUser() returns null.

How does my Android app let RequestFactory know who is logged in?

This question applies to dev mode and production mode.

Thanks.


Solution

  • There is a not-so-obvious answer found in the old AppEngine Connected Android Eclipse wizard code, which is no longer available in the GPE (see Util.java of this wizard generated code). It includes the following:

    T requestFactory = RequestFactorySource.create(factoryClass);
    requestFactory.initialize(new SimpleEventBus(),
                new AndroidRequestTransport(uri, authCookie));
    

    with

    public AndroidRequestTransport(URI uri, String cookie) {
            this.uri = uri;
            this.cookie = cookie;
        }
    
        public void send(String payload, TransportReceiver receiver) {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost();
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setHeader("Cookie", cookie);
    
            post.setURI(uri);
            Throwable ex;
            try {
                post.setEntity(new StringEntity(payload, "UTF-8"));
                HttpResponse response = client.execute(post);
                if (200 == response.getStatusLine().getStatusCode()) {
                    String contents = readStreamAsString(response.getEntity().getContent());
                    receiver.onTransportSuccess(contents);
                } else {
                    receiver.onTransportFailure(new ServerFailure(response.getStatusLine()
                            .getReasonPhrase()));
                }
                return;
            } catch (UnsupportedEncodingException e) {
                ex = e;
            } catch (ClientProtocolException e) {
                ex = e;
            } catch (IOException e) {
                ex = e;
            }
            receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
        }
    

    Using that code from the GPE wizard did the trick for me.