开发者

Android app uploading data to a python server via post

I have su开发者_开发技巧ccessfully implemented this from android to a java httpservlet on google app engine, but I'd like to use python instead for the server side. I'm new to python. Has anyone done this? I have the guestbook example up and running, but I can't seem to send posts from my android app to the server.

I'd also like to issue a string response back to the client like "success".

A guiding hand would be much appreciated.

Thanks

***Client side java:

URL url = new URL(Const.SERVER_NAME);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
    connection.getOutputStream()
);
out.write("content=12345");
out.close();

***Server side Python:

class Upload(webapp.RequestHandler):
    def post(self):
        greeting.content = self.request.get('content') 
        greeting.put()

***Server side Java (working)

public void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException
{

    try {
        String instring = request.getParameter("content")

        // set the response code and write the response data
        response.setStatus(HttpServletResponse.SC_OK);
        OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());

        writer.write("Success");
        writer.flush();
        writer.close();
    } catch (IOException e) {
        try{
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().print(e.getMessage());
            response.getWriter().close();
        } catch (IOException ioe) {
        }
    } 


I know it's been a long time. But I did solve this so I'll post the solution.

Android code:

        url = new URL(SERVER_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(
                                  connection.getOutputStream());

        String post_string;
        post_string = "deviceID="+tm.getDeviceId().toString();

        // send post string to server
        out.write(post_string);
        out.close();

        //grab a return string from server
        BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    connection.getInputStream()));

        Toast.makeText(context, in.readLine(), Toast.LENGTH_SHORT).show();

And here's the python server side, using Django with GAE:

def upload(request):
    if request.method == 'POST':
        deviceID = measurement.deviceID = str(request.POST['deviceID'])
        return HttpResponse('Success!')
    else:
        return HttpResponse('Invalid Data')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜