簡體   English   中英

獲取java.io.IOException:在getInputStream上寫入服務器時出錯

[英]Getting java.io.IOException: Error writing to server at getInputStream

如果臨時字符串很大,則會得到java.io.IOException:在getInputStream上寫入服務器時出錯

String tmp  = js.deepSerialize(taskEx);
URL url = new URL("http://"
                    + "localhost"
                    + ":"
                    + "8080"
                    + "/Myproject/TestServletUpdated?command=startTask&taskeId=" +taskId + "'&jsonInput={\"result\":"
                    + URLEncoder.encode(tmp) + "}"); 

                    URLConnection conn = url.openConnection();
                     InputStream is = conn.getInputStream();

這是為什么? 該調用轉到URL中提到的servlet。

使用HTTP POST方法,而不是將所有數據放在GET方法的URL中。 URL的長度有上限,因此如果要發送任意長度的數據,則需要使用POST方法。

您可能需要將URL修改為http://localhost:8080/Myproject/TestServletUpdated ,然后將其余的放入

command = "startTask&taskeId=" + taskId + "'&jsonInput={\"result\":" + URLEncoder.encode(tmp) + "}"

在POST請求的正文中。

我認為您可能有一個“網址太長”,最大字符數為2000( 有關更多信息,請參見此SO帖子 )。 不會發出GET請求來處理如此長的數據輸入。

如果還可以更改servlet代碼,則可以將其更改為POST而不是GET請求(如您現在的要求)。 客戶端代碼看起來很類似:

public static void main(String[] args) throws IOException {

    URL url = new URL("http", "localhost:8080", "/Myproject/TestServletUpdated");

    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write("command=startTask" +
             "&taskeId=" +taskId +
             "&jsonInput={\"result\":" + URLEncoder.encode(tmp) + "}");
    wr.flush();


    .... handle the answer ...
}

我沒有首先看到它,但似乎您的請求字符串中有一個單引號字符。

...sk&taskeId=" + taskId + "'&jso.....
                            ^

嘗試將其刪除,可能會對您有所幫助!

這可能是因為請求是作為GET發送的,該GET字符數受到限制。 當超出限制時,將得到IOException 將其轉換為POST ,它應該可以工作。

對於POST

URLConnection conn = url.openConnection().
OutputStream writer = conn.getOutputSteam();
writer.write("yourString".toBytes());

從您傳遞的網址中刪除臨時字符串。 在上面的代碼中將“命令”字符串移動到"yourString".toBytes()部分

getInputStream()用於讀取數據。 使用getOutputStream()

暫無
暫無

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

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