我是Java的新手,在使用HTTPURLConnection在Android上发送多个发布请求时遇到上述错误。我已经写了一个HTTPTransport类,其中我想要sendMessage和recvMessage方法。HTTPUrlConnection错误(从inputStream中读取后无法打开OutputStream)
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和recvMessage成功发送第一条消息。当我尝试发送第二个错误时,我看到以下错误: IOException:java.net.ProtocolException:从输入流读取后无法打开OutputStream
请让我知道如何编写此类。
谢谢!
我很抱歉,但由于我对Java很陌生,所以我不明白你的回应。 – smitten 2011-01-12 22:55:06