接收GET请求而不是POST

时间:2018-09-06 04:36:56

标签: java php post get

我正在尝试创建客户端服务器应用程序,但目前仍处于停滞状态。我的客户端上有此Java代码。

        HttpURLConnection connection;
        connection = (HttpURLConnection) new URL("http://www.masterpaint.gr/login.php").openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
        connection.setRequestProperty("Accept","application/json: charset=UTF-8");
        connection.setRequestMethod("POST");

        System.out.println("The request method on client end is " + connection.getRequestMethod());
        System.out.println("Server response to connection " + connection.getResponseMessage());

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String buffer;
        StringBuilder stringBuilder = new StringBuilder();
        while ((buffer = reader.readLine()) != null) {
            stringBuilder.append(buffer);
        }
        System.out.println("The request methond on server end is " + stringBuilder.toString()); 

这是服务器上的简单测试php代码。

  <?php   echo $_SERVER['REQUEST_METHOD'];  ?>

每当我运行此测试Java程序并尝试连接时,我都会得到相同的输出。

客户端的请求方法是POST
服务器对连接的响应正常
服务器端的请求方法是GET

php脚本总是回显我正在发送GET请求,即使 我的Java代码指出使用POST。我尝试使用不同的请求方法通过邮递员连接到脚本,而且一切都很好,因此问题一定出在Java代码中。任何见识将不胜感激。

1 个答案:

答案 0 :(得分:0)

我没有任何php经验,但似乎正在寻找不会发送给您的情况下的内容长度标头,因此将其视为GET请求。

HttpURLConnection connection;
         connection = (HttpURLConnection) new URL("http://www.masterpaint.gr/login.php").openConnection();
         connection.setDoOutput(true);
         connection.setDoInput(true);
         connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
         connection.setRequestProperty("Accept","application/json: charset=UTF-8");
         connection.setRequestMethod("POST");
         connection.setFixedLengthStreamingMode(0);
         System.out.println("The request method on client end is " + connection.getRequestMethod());
         System.out.println("Server response to connection " + connection.getResponseMessage());

         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         String buffer;
         StringBuilder stringBuilder = new StringBuilder();
         while ((buffer = reader.readLine()) != null) {
             stringBuilder.append(buffer);
         }
         System.out.println("The request methond on server end is " + stringBuilder.toString()); 

这将设置内容长度为0,因为您没有发送任何内容。