15

我正在编写一个连接到 servlet 的程序,这要归功于 aHttpURLConnection但我在检查 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 但不幸的是没有它它可以正常工作,我需要检查 url 所以我认为问题来自getResponseCode方法但我不知道如何解决它

非常感谢你

4

4 回答 4

27

HTTP 协议基于请求-响应模式:您首先发送请求,然后服务器响应。一旦服务器响应,您就不能再发送任何内容,这没有任何意义。(服务器如何在知道您要发送的内容之前给您响应代码?)

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

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

于 2012-07-10T12:15:25.610 回答
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;
     }
 }
于 2012-07-10T12:16:37.800 回答
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);
...
于 2014-09-17T21:47:32.770 回答
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();
于 2016-12-10T02:26:51.353 回答