Java HTTPUrlConnection错误(从inputStream读取后无法打开OutputStream)
我是Java新手,在Android上使用HTTPURLConnection发送多个post请求时遇到上述错误。我已经编写了一个HTTPTransport类,希望在其中包含sendMessage和RecVMMessage方法Java HTTPUrlConnection错误(从inputStream读取后无法打开OutputStream),java,exception,protocols,httpurlconnection,Java,Exception,Protocols,Httpurlconnection,我是Java新手,在Android上使用HTTPURLConnection发送多个post请求时遇到上述错误。我已经编写了一个HTTPTransport类,希望在其中包含sendMessage和RecVMMessage方法 public class HTTPTransport { private HttpURLConnection connection; public HTTPTransport() { URL url = new URL("http://test
public class HTTPTransport
{
private HttpURLConnection connection;
public HTTPTransport()
{
URL url = new URL("http://test.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setRequestProperty("Connection", "Keep-Alive");
}
public void sendMessage(byte[] msgBuffer, long size)
{
try
{
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.write(msgBuffer, 0, (int)size);
dos.flush();
dos.close();
dos.close();
}
catch( IOException e )
{
// This exception gets triggered with the message mentioned in the title.
Log.e(TAG, "IOException: " + e.toString());
}
}
public byte[] recvMessage()
{
int readBufLen = 1024;
byte[] buffer = new byte[readBufLen];
int len = 0;
FileOutputStream fos = new FileOutputStream(new File("/sdcard/output.raw"));
DataInputStream dis = new DataInputStream(connection.getInputStream());
while((len = dis.read(buffer, 0, readBufLen)) > 0)
{
Log.d(TAG, "Len of recd bytes " + len + ", Byte 0 = " + buffer[0]);
//Save response to a file
fos.write(buffer, 0, len);
}
fos.close();
dis.close();
return RecdMessage;
}
}
我能够使用sendMessage和RecVMMessage成功发送第一条消息。当我尝试发送第二个时,我看到以下错误:
IOException:java.net.ProtocolException:从inputStream读取后无法打开OutputStream
请告诉我如何写这门课
谢谢 您的
HTTPUrlConnection
实现。我相信您必须使用一个HttpConnectionManager
以您想要的方式使用Keep-Alive。您需要为每个请求使用一个新的HttpURLConnection。TCP连接本身将在幕后汇集。不要自己尝试这样做。很抱歉,因为我对Java非常陌生,所以我不理解您的回答。这有帮助吗?谢谢,我会看一下。我从这个文档中得到的只是应该关闭inputstream,以改进您在使HTTP连接持久化方面所做的更改。我想我已经这样做了。我现在改用HTTPClient。到目前为止,它似乎正在发挥作用。