我正在嘗試製作一個可以接受GET和POST HTTP請求的java服務器。現在我設法讓GET方法起作用。但我沒有設法讓POST方法工作。我的服務器設法讀取請求頭,但似乎沒有讀取消息的正文。即發佈的內容。這裏是代碼:讓HTTP POST在製作自己的Java服務器時工作
int port = 1991;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("The Server is on and listening on port " + port);
System.out.println(" ");
while (true)
{
Socket ClientSocketConnection = serverSocket.accept();
System.err.println("We have established a connection with a client!");
System.out.println(" ");
BufferedReader ServerInput = new BufferedReader(new InputStreamReader(ClientSocketConnection.getInputStream()));
DataOutputStream ServerOutput =new DataOutputStream(ClientSocketConnection.getOutputStream());
String StringInput;
int iCount = 0;
int CountNull = 0;
while ((StringInput = ServerInput.readLine()) != null)
{
System.out.println(StringInput);
}
現在我只顯示通過套接字發送的所有東西。但由於某些原因,我只是不明白的請求消息的身體,我知道身體是因爲在鉻送我有這樣的:
我不知道怎麼去說,「表單數據」。任何幫助將非常感謝!
UPDATE:
這裏的問題是進一步收窄。從發送HTTP請求罰款。使用HTTP POST方法,我們將請求標頭設爲\ r \ n,然後是消息數據。問題是當我的BufferedData變量ServerInput
讀入\ r \ n(空行)時,它停止從ServerInput
讀取數據。有任何解決這個問題的方法嗎?
您是否收到「Content-length」標頭?如果是這樣,那麼在讀取一個空行(表示頭部分的結尾)後,讀取_Content-length_字節數並將它們轉換爲字符串。你的問題可能是在你的ServerInput的末尾沒有行結束,因此readLine()會永遠等待它。 – halfbit
事實上,我確實得到了12的Content-Legnth。我現在會嘗試你的建議 – user481610