Java中的发布请求参数不起作用

时间:2016-05-31 19:29:38

标签: java android database web-services

我试图处理从java文件到PLAY服务器的POST请求。在服务器上,我将参数打印为request().body().asText(),如果我在终端中使用curl命令,则该参数有效。但是,如果我尝试使用java文件进行POST,它始终会打印null。我已尝试过此网站的多个示例,但它始终打印null。 (但我确实得到了正确的返回值,所以我确实连接了服务器。)

import java.lang.*;
import java.net.*;
import java.io.*;
import java.util.*;

public class javaa{
public static void main(String[] args){
     try{
          String urlParameters = "param1=a&param2=b&param3=c";
          URL url = new URL("http://localhost:9000/createPerson");
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();

          conn.setDoOutput(true);

          OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

          writer.write(urlParameters);
          writer.flush();

          String line;
          BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

          while ((line = reader.readLine()) != null) {
              System.out.println(line);
          } 
          reader.close();
          writer.close();
          conn.disconnect();
     }
     catch(Exception e){
          System.out.println(e);
     }
}
}

1 个答案:

答案 0 :(得分:0)

您忘记设置方法POST确实默认为GET,可以通过添加

来完成
 conn.setRequestMethod("POST");

您还应将内容类型设置为application/x-www-form-urlencoded,如下所示:

conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

您还应该向服务器指出下一个身体的大小:

byte[] requestBody = urlParameters.getBytes("UTF-8");
conn.setFixedLengthStreamingMode(requestBody.length);

所以最后代码看起来像这样:

conn.setRequestMethod("POST");
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
byte[] requestBody = urlParameters.getBytes("UTF-8");
conn.setFixedLengthStreamingMode(requestBody.length);
try (OutputStream out = conn.getOutputStream()) {
    out.write(requestBody);
    out.flush();
}

响应更新

根据您的意见,您应该重试:

conn.addRequestProperty("Content-Type", "text/plain");

而不是:

conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");