15

のおかげでサーブレットに接続するプログラムを書いているのですHttpURLConnectionが、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

私もこの問題を抱えています。驚いたことに、追加したコードが原因でエラーが発生したことです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 に答える
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 に答える