簡體   English   中英

Java不發送HTTP POST請求

[英]Java doesn't send HTTP POST Request

我正在實現一些簡單的Java類,以便使用POST方法發送HTTP請求,還實現了另一個Java類,以便接收它。
當我通過瀏覽器(Chrome)或應用程序(在這種情況下使用Postman)發出POST請求時,服務器工作正常,但是當我使用Java發送HTTP請求時,服務器最終會出現問題!

我發送的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();

也許發件人網址中的“ localhost”不能解析為服務器綁定到的同一個IP? 嘗試更改為127.0.0.1或您的實際IP地址。

嘗試使用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();

使用瀏覽器發送POST表單時,它將以RFC1866定義的某種格式發送表單,您在發出發布請求時必須在Java上重新創建該表單

使用這種格式,將Content-Type標頭設置為application/x-www-form-urlencoded ,並像在帶有get請求的url中那樣傳遞正文,這很重要。

在Java中借用我以前對POST答案的一些代碼:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM