读取输入后无法写入输出

时间:2012-07-10 12:10:50

标签: java httpurlconnection

由于HttpURLConnection,我正在编写一个连接到servlet的程序,但是在检查URL时卡住了

public void connect (String method) throws Exception {

server = (HttpURLConnection) url.openConnection ();
server.setDoInput (true);
server.setDoOutput (true);
server.setUseCaches (false);
server.setRequestMethod (method);
server.setRequestProperty ("Content-Type", "application / xml");

server.connect ();

/*if (server.getResponseCode () == 200)
{
System.out.println ("Connection OK at the url:" + url);
System.out.println ("------------------------------------------- ------- ");
}
else
System.out.println ("Connection failed"); 

}*/

我收到了错误:

  

java.net.ProtocolException:读取输入后无法写入输出。

如果我用注释中的代码检查url,但没有它就可以正常工作 不幸的是,我需要检查网址,所以我认为问题来自getResponseCode方法,但我不知道如何解决它

非常感谢

4 个答案:

答案 0 :(得分:25)

HTTP协议基于请求 - 响应模式:您首先发送请求,服务器响应。一旦服务器响应,您就无法发送更多内容,这是没有意义的。 (服务器如何在之前为您提供响应代码它知道您要发送的是什么?)

因此,当您致电server.getResponseCode()时,您有效地告诉服务器您的请求已完成并且可以处理它。如果要发送更多数据,则必须开始新请求。

查看您的代码,您要检查连接本身是否成功,但不需要:如果连接不成功,Exception会抛出server.connect()。但是连接尝试的结果与HTTP响应代码不同,HTTP响应代码总是在服务器处理完所有输入之后。

答案 1 :(得分:7)

我认为异常不是由printing url引起的。在读取响应之后,应该尝试编写一些代码来设置请​​求体。

如果您在获取HttpURLConnection.getOutputStream()

后尝试获取HttpURLConnection.getInputStream(),则会发生此异常

这是sun.net.www.protocol.http.HttpURLConnection.getOutputStream的实现:

public synchronized OutputStream getOutputStream() throws IOException {

     try {
         if (!doOutput) {
             throw new ProtocolException("cannot write to a URLConnection"
                            + " if doOutput=false - call setDoOutput(true)");
         }

         if (method.equals("GET")) {
             method = "POST"; // Backward compatibility
         }
         if (!"POST".equals(method) && !"PUT".equals(method) &&
             "http".equals(url.getProtocol())) {
             throw new ProtocolException("HTTP method " + method +
                                         " doesn't support output");
         }

         // if there's already an input stream open, throw an exception
         if (inputStream != null) {
             throw new ProtocolException("Cannot write output after reading 
                input.");
         }

         if (!checkReuseConnection())
             connect();

         /* REMIND: This exists to fix the HttpsURLConnection subclass.
          * Hotjava needs to run on JDK.FCS.  Do proper fix in subclass
          * for . and remove this.
          */

         if (streaming() && strOutputStream == null) {
             writeRequests();
         }
         ps = (PrintStream)http.getOutputStream();
         if (streaming()) {
             if (strOutputStream == null) {
                 if (fixedContentLength != -) {
                     strOutputStream = 
                        new StreamingOutputStream (ps, fixedContentLength);
                 } else if (chunkLength != -) {
                     strOutputStream = new StreamingOutputStream(
                         new ChunkedOutputStream (ps, chunkLength), -);
                 }
             }
             return strOutputStream;
         } else {
             if (poster == null) {
                 poster = new PosterOutputStream();
             }
             return poster;
         }
     } catch (RuntimeException e) {
         disconnectInternal();
         throw e;
     } catch (IOException e) {
         disconnectInternal();
         throw e;
     }
 }

答案 2 :(得分:1)

我遇到了同样的问题。 该问题的解决方案是您需要使用序列

openConnection -> getOutputStream -> write -> getInputStream -> read

这意味着......:

public String sendReceive(String url, String toSend) {
URL url = new URL(url);
URLConnection conn = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.sets...

OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(toSend);
out.close();

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String receive = "";
do {
    String line = in.readLine();
    if (line == null)
        break;
    receive += line;
} while (true);
in.close();

return receive;
}

String results1 = sendReceive("site.com/update.php", params1);
String results2 = sendReceive("site.com/update.php", params2);
...

答案 3 :(得分:1)

我也有这个问题,令我惊讶的是错误是由我添加的代码System.out.println(conn.getHeaderFields());

引起的

以下是我的代码:

HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
configureConnection(conn);
//System.out.println(conn.getHeaderFields()); //if i comment this code,everything is ok, if not the 'Cannot write output after reading input' error happens
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(paramsContent.getBytes());
os.flush();
os.close();