【问题标题】:Receiving a GET request instead of POST接收 GET 请求而不是 POST
【发布时间】:2018-09-06 04:36:55
【问题描述】:

我正在尝试创建一个客户端服务器应用程序,但目前卡住了。我的客户端上有这个 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代码中。任何见解将不胜感激。

【问题讨论】:

标签: java php post get


【解决方案1】:

我没有任何 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,因为您不发送任何内容。

【讨论】:

  • 我试过它现在可以工作了,因为它已经被临时移动了,所以它给出了异常。只需根据你的代码检查我编辑的答案
猜你喜欢
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 2020-11-12
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
相关资源
最近更新 更多