【问题标题】:Getting java.io.IOException: Error writing to server at getInputStream获取 java.io.IOException:在 getInputStream 写入服务器时出错
【发布时间】:2012-06-09 10:15:05
【问题描述】:

如果临时字符串非常大,我会得到 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();

这是为什么呢? 此调用转到 URL 中提到的 servlet。

【问题讨论】:

  • 鉴于它是本地的,您应该能够看到服务器端发生了什么。检查异常。此外,可能还有比您在此处显示的消息更多的信息 - 是否存在内部异常?
  • URL 的最大长度有限制。见:stackoverflow.com/questions/417142/…
  • @MaciejTrybiło ys 我想这就是问题所在,还有其他方法吗??
  • 您可以尝试使用 POST 请求进行操作。下面是一个例子:exampledepot.com/egs/java.net/post.html 抱歉回答了一点问题!

标签: java json url servlets


【解决方案1】:

这可能是因为请求是作为GET 发送的,它有几个字符的限制。当超出限制时,您会得到一个IOException。将其转换为POST,它应该可以工作。

对于POST

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

从您传递的 url 中删除临时字符串。将“command”字符串移动到上面代码中的"yourString".toBytes()部分

【讨论】:

  • url中没有名为url.getOutputStream()的方法
【解决方案2】:

使用 HTTP POST 方法,而不是将所有数据放在 GET 方法的 URL 中。 URL 的长度是有上限的,所以如果要发送任意长度的数据,需要使用 POST 方法。

你可能想把 URL 修改为http://localhost:8080/Myproject/TestServletUpdated,剩下的就放上去

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

在 POST 请求的正文中。

【讨论】:

  • 我如何在上面的 URL 中更改它?
【解决方案3】:

我认为您可能有一个“网址太长”,最大字符数为 2000 (see this SO post for more info)。 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.....
                            ^

尝试删除它,它可能会帮助你!

【讨论】:

    【解决方案4】:

    getInputStream() 用于读取数据。使用 getOutputStream()

    【讨论】:

      猜你喜欢
      • 2014-11-20
      • 2015-11-02
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多