Java不发送HTTP POST请求

时间:2018-10-24 17:38:24

标签: java http post

我正在实现一些简单的Java类,以便通过HTTP方法发送POST请求,并实现另一个Java类,以便接收请求。
当我通过浏览器(Chrome)或应用程序(在这种情况下使用Postman)发出POST请求时,服务器工作正常,但是当我发送HTTP请求时,服务器最终出现问题用Java!

我发送的HTTP类是“ Sender.java”,其中包含以下代码段:

String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// Setting basic post request
con.setRequestMethod("POST");       
//con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//con.setRequestProperty("Content-Type","text/plain");

// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write("Just Some Text".getBytes("UTF-8"));
os.flush();
os.close();
//connect to the Server(resides at Server.java)
con.connect();

我已经注释了几行代码设置标头,例如“ Accept-Language”和“ Content-Type”,因为我不知道Java程序是否需要这些标头?
< / p>

服务器是另一个名为“ Server.java”的Java程序。这是与读取Sender.java发出的HTTP请求有关的代码段。(如果需要)。

int servPort = 8082;
// Create a server socket to accept HTTP client connection requests
HttpServer server = HttpServer.create(new InetSocketAddress(servPort), 0);
System.out.println("server started at " + servPort);

server.createContext("/", new PostHandler());//PostHandler implements HttpHandler
server.setExecutor(null);

server.start();

我想要做的就是使用HTTP方法将纯文本作为Post请求的正文发送。我已经阅读了很多站点,甚至在此站点上有相关问题。但它仍然无法解决。换句话说,每当我从“ Sender.java”创建一个HTTP请求时,“ Server.java”都不会出现任何内容。我只想知道我的摘要有什么问题,应该如何解决?

4 个答案:

答案 0 :(得分:1)

我对此进行了测试,并且可以正常工作

//Sender.java
String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();


con.setRequestMethod("POST");       
con.setDoOutput(true);

OutputStream os = con.getOutputStream();
os.write("Just Some Text".getBytes("UTF-8"));
os.flush();

int httpResult = con.getResponseCode(); 
con.disconnect();

如您所见,连接不是必需的。关键行是

  

int httpResult = con.getResponseCode();

答案 1 :(得分:0)

也许发件人URL中的“ localhost”不能解析为服务器绑定到的同一个IP?尝试更改为127.0.0.1或您的实际IP地址。

答案 2 :(得分:0)

尝试使用PrintStream

        String url = "http://localhost:8082/";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Setting basic post request
        con.setRequestMethod("POST");       
        //con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //con.setRequestProperty("Content-Type","text/plain");

        // Send post request
        con.setDoOutput(true);
        OutputStream os = con.getOutputStream();
        java.io.PrintStream printStream = new java.io.PrintStream(os);
        printStream.println("Just Some Text");
        con.getInputStream();//Send request
        os.flush();
        os.close();

答案 3 :(得分:0)

当您使用浏览器发送POST表单时,它以RFC1866中定义的某种格式发送表单,您在发出发布请求时必须在Java上重新创建它。

使用这种格式,很重要的一点是将Content-Type标头设置为application/x-www-form-urlencoded,并像在带有get请求的url中那样传递正文。

Borrowing some code of my previous answer to POST in Java:

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// Setting basic post request
con.setRequestMethod("POST");    

Map<String,String> form = new HashMap<>();

// Define the fields
form.put("username", "root");
form.put("password", "sjh76HSn!"); // This is a fake password obviously

// Build the body
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
    sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" 
         + URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;

// Prepare our `con` object
con.setFixedLengthStreamingMode(length);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.connect();
try (OutputStream os = con.getOutputStream()) {
    os.write(out);
}