gpt4 book ai didi

java - HTTPUrlConnection 错误(从 inputStream 读取后无法打开 OutputStream)

转载 作者:行者123 更新时间:2023-12-02 09:14:20 26 4
gpt4 key购买 nike

我是 Java 新手,在 Android 上使用 HTTPURLConnection 发送多个 POST 请求时遇到上述错误。我编写了一个 HTTPTransport 类,我希望在其中具有 sendMessage 和 receiveMessage 方法。

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:从 inputStream 读取后无法打开 OutputStream

请告诉我如何编写这门课。

谢谢!

最佳答案

您的 HTTPUrlConnection 实现 does not allow you to reuse the connection in this manner 。我相信您必须使用 HttpConnectionManager 才能以您想要的方式使用 Keep-Alive。

关于java - HTTPUrlConnection 错误(从 inputStream 读取后无法打开 OutputStream),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4673289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com