我有一个简短的Android-Java客户端程序,该程序使用POST方法将基本信息发送到bottle-python服务器。在第一个版本的代码中,服务器不显示任何内容。但是,在第二个版本中它可以工作,但是我无法理解这条额外的行的作用,因为它与发布内容有关。我真的很感谢有人帮我解决这个问题(服务器代码没有错,因为我可以使用python请求和浏览器正确发送请求)。
这是客户端代码的第一个版本:
String url = "http://192.168.1.23:8080/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
PrintStream myPusher = new PrintStream(os );
myPusher.print("param1=hey");
第二版:
String url = "http://192.168.1.23:8080/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
PrintStream myPusher = new PrintStream(os );
myPusher.print("param1=hey");
InputStream in= con.getInputStream(); //Nothing changed but only this additional line
Bottle(python)服务器:
@app.route('/', method="POST")
def hello():
print("it works")
name = request.forms.get("param1")
print(name)
return name
@app.route('/')
def hello():
i=0
print("it works")
run(app, host="192.168.1.23", port=8080)
与第一个客户端代码服务器什么都不显示。
随着第二个代码服务器显示:
it works
hey
192.168.1.24 - - [31/Dec/2018 17:10:28] "POST / HTTP/1.1" 200 3
这是我所期望的。
最佳答案
在第一个代码段中,输出流仍处于打开状态。因此服务器不知道它是否收到完整的请求。可能只是关闭流也可以。
但是,我至少会调用getResponseCode
来查看请求的结果。