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

匿名 (未验证) 提交于 2019-12-03 00:45:01

问题:

If the temp string is very large I get java.io.IOException: Error writing to server at 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(); 

Why is that? This call goes to the servlet mentioned in the URL.

回答1:

I think you might have a "too long url", the maximum number of characters are 2000 (see this SO post for more info). GET requests are not made to handle such long data input.

You can, if you can change the servlet code also, change it into a POST instead of a GET request (as you have today). The client code would look pretty simular:

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 ... } 

I didn't see it first but it seems like you have a single quote character in your request string.

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

try removing it, it might help you!



回答2:

Use HTTP POST method instead of putting all the data in the URL for GET method. There is an upper limit for the length of the URL, so you need to use POST method if you want to send arbitrary length data.

You may want to modify the URL to http://localhost:8080/Myproject/TestServletUpdated, and put the rest

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

in the body of the POST request.



回答3:

getInputStream() is used to read data. Use getOutputStream()



回答4:

It could be because the request is being sent as a GET which has a limitation of a very few characters. When the limit exceeds you get an IOException. Convert that to POST and it should work.

For POST

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

Remove the temp string from the url that you are passing. Move the "command" string to the "yourString".toBytes() section in the code above



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!