我正在实现一些简单的 java 类,以便使用 POST
方法发送 HTTP
请求,并实现另一个 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程序是否需要这些标题?
服务器是另一个名为“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();
我想要的只是使用 Post
方法发送明文作为我的 HTTP
请求的正文。我读过很多网站,甚至在这个网站上阅读了相关问题。但仍然没有成功。换句话说,每当我从“Sender.java”创建 HTTP
请求时,“Server.java”中什么也不会出现。我只是想知道我的片段有什么问题以及应该如何解决?
最佳答案
我测试了这个并且它有效:
//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();
关于Java不发送HTTP POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52975002/