gpt4 book ai didi

java - Android 应用程序通过 post 将数据上传到 python 服务器

转载 作者:可可西里 更新时间:2023-11-01 17:04:10 25 4
gpt4 key购买 nike

我已经成功地将此从 android 实现到 google app engine 上的 java httpservlet,但我想在服务器端使用 python。我是 python 的新手。有没有人这样做过?我已经启动并运行了留言簿示例,但我似乎无法将帖子从我的 android 应用程序发送到服务器。

我还想向客户端发出一个字符串响应,例如“成功”。

指导之手将不胜感激。

谢谢

***客户端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();

***服务器端 Python:

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

***服务器端Java(工作)

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

最佳答案

我知道已经很久了。但我确实解决了这个问题,所以我会发布解决方案。

安卓代码:

        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();

这里是 python 服务器端,使用 Django 和 GAE:

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

关于java - Android 应用程序通过 post 将数据上传到 python 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2331862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com