POST请求未发送

时间:2018-12-31 14:20:49

标签: java android bottle

我有一个简短的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

瓶子(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

那是我所期望的。

3 个答案:

答案 0 :(得分:1)

PrintStream 是一种缓冲类型,这意味着您应该在每个print()之后添加刷新操作,或者改用println()

答案 1 :(得分:0)

在您的第一个代码段中,输出流仍处于打开状态。因此服务器不知道它是否收到完整的请求。也许只需关闭流也可以。

但是,我至少会打电话给getResponseCode来查看请求的结果。

答案 2 :(得分:0)

您的Java代码似乎不完整,无法发送发布请求。 我认为通过使用this code,您可以自己使用它。