Search code examples
androidpythongoogle-app-enginewebapp2

How to receive and return string in webapp2 from android?


I am struggling to receive a string into my webapp2 server. The android device is supposed to send a string nameto the server then the server returns back to the phone "your name is: " + name.

The server is only returning to android"your name is: " because the name string seems to be null on the server side. I am not sure if the problem is on android or server side.

My code is as follows:

ANDROID.java

Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try  {
                    String name = "Jay";
                    String serverURL = "http://myapp.appspot.com";
                    URL url = new URL(serverURL);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    try{
                        httpURLConnection.setReadTimeout(15000);
                        httpURLConnection.setConnectTimeout(15000);
                        httpURLConnection.setRequestMethod("POST");
                        httpURLConnection.setDoOutput(true);
                        httpURLConnection.setDoInput(true);

                        OutputStream outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                        String post_data = URLEncoder.encode(name,"UTF-8");
                        writer.write(post_data);
                        writer.flush();
                        writer.close();
                        outputStream.close();

                        InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                        String result="";
                        String line="";
                        while((line = reader.readLine())!= null)
                            result += line;
                        reader.close();
                        inputStream.close();

                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } finally {
                        httpURLConnection.disconnect();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();

SERVER.py

import webapp2


class MainHandler(webapp2.RequestHandler):

    def post(self):
        name = self.request.get('content')
        self.response.out.write("Your name is: " + name)

    def get(self):
        self.response.write("Hello World")


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

Solution

  • Your name = self.request.get('content') statement most likely doesn't do what you're expecting it to.

    Since post data is sent in the message body you probably want to look at self.request.body instead (I'm not a java user, I can't tell exactly how your post data is organized inside the body).

    From webapp2's Request data:

    POST data

    Variables url encoded in the body of a request (generally a POST form submitted using the application/x-www-form-urlencoded media type) are available in request.POST. It is also a MultiDict and can be accessed in the same way as .GET. Examples:

    request = Request.blank('/')
    request.method = 'POST'
    request.body = 'check=a&check=b&name=Bob'
    
    # The whole MultiDict:
    # POST([('check', 'a'), ('check', 'b'), ('name', 'Bob')])
    post_values = request.POST
    
    # The last value for a key: 'b'
    check_value = request.POST['check']
    
    # All values for a key: ['a', 'b']
    check_values = request.POST.getall('check')
    
    # An iterable with all items in the MultiDict:
    # [('check', 'a'), ('check', 'b'), ('name', 'Bob')]
    request.POST.items()
    

    Like GET, the name POST is a somewhat misleading, but has historical reasons: they are also available when the HTTP method is PUT, and not only POST.