收到带有 JSON 正文的响应时,我遇到了类似的问题。经过几次实验,我检测到该程序在读取正文时挂起。所以,我解决了这个问题,通过从标题中读取 Content-Length ,在空白行(在 header 和 body 之间)之后停止,然后只读取必要的字符。这是代码:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class TelegramSocketClient {
private final String CONTENT_LEN = "Content-Length:";
Socket clientSocket;
SSLSocket sslSocket;
PrintWriter out;
BufferedReader in;
public void startSSLConnection(String ip, int port) throws IOException {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory
.getDefault();
sslSocket = (SSLSocket) factory.createSocket(ip, port);
out = new PrintWriter(sslSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(sslSocket.getInputStream(), StandardCharsets.UTF_8));
}
public String sendMessage(String msg) throws IOException {
out.println(msg);
String line = null;
int contentLen = 0;
while ((line = in.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
if(line.startsWith(CONTENT_LEN)) {
contentLen = Integer.parseInt(line.substring(CONTENT_LEN.length() +1, line.length()));
}
}
char [] buff = new char[contentLen];
in.read(buff, 0, buff.length);
return new String(buff, 0, buff.length);
}
public void stopConnection() throws IOException {
in.close();
out.close();
clientSocket.close();
}
}