1

我在创建 httpurlconnection(或 httpsurlconnection)时遇到问题。实际上这是关于在转换 url.openconnection 之后设置连接头。在运行相同的代码之前,现在没有运行。我无法理解。(例外:已经连接......或喜欢......)

有时它会一直运行到httpConn.getOutPutStream(); 此时它给出错误“java.net.ProtocolException:OutputStream 不可用,因为请求标头已经发送!”

我的错在哪里??

在我使用代码之前:所有代码都在这里(我也有关于此代码的另一个问题)

URL url = new URL(getUrl());
URLConnection conn = url.openConnection();
HttpURLConnection httpConn=(HttpURLConnection)conn; /*or HttpsURLConnection*/
httpConn.set...
...
httpConn.connect();
...

我尝试在 cast 后设置一些设置,但结果是一样的。conn.set .. 的工作,但铸造后我不能设置任何东西......

更改代码:

        URL url = new URL(getUrl());
        conn = url.openConnection();
        conn.setAllowUserInteraction(false);
        conn.setConnectTimeout(10000);
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("Content-Type",
                "text/xml; charset=utf-8");
        conn.setRequestProperty("SOAPAction",
                "http://tempuri.org/IAuthenticationServiceNew/Authenticate");
        conn.setRequestProperty("Software-Version", AppData.VERSION);
        conn.setDoOutput(true);
        httpConn = (HttpsURLConnection) conn;
        httpConn.setChunkedStreamingMode(getParams().getBytes("UTF8").length);
        httpConn.setInstanceFollowRedirects(true);

        httpConn.connect();
        os = httpConn.getOutputStream();
        os.write(getParams().getBytes("UTF8"));
4

1 回答 1

1

这是正确的!
"httpConn.setInstanceFollowRedirects(true)" 连接并将标头发送到服务器。我关闭了这段代码。

        URL url = new URL(getUrl());
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        httpConn.setAllowUserInteraction(false);
        httpConn.setUseCaches(false);
        httpConn.setConnectTimeout(10000);
        httpConn.setRequestProperty("Accept-Charset", "utf-8");
        httpConn.setRequestProperty("Content-Type",
                "text/xml; charset=utf-8");
        httpConn.setRequestProperty("SOAPAction",
                "http://tempuri.org/IAuthenticationServiceNew/"
                        + conTypeString);
        httpConn.setRequestProperty("Software-Version", AppData.VERSION);
        httpConn.setRequestMethod("POST");
        httpConn.setChunkedStreamingMode(0);
        os = httpConn.getOutputStream();
        os.write(getParams().getBytes("UTF8"));
于 2011-10-17T10:58:29.257 回答