Java 错误情况下的端口更改:HttpURLConnection

Java 错误情况下的端口更改:HttpURLConnection,java,android,http,Java,Android,Http,我在android应用程序中使用HttpURLConnection使用API,运行正常,但如果我收到响应代码,但200 ok(如404500)除外,则当我在错误响应代码后点击下一个请求时,我的端口正在更改: 下面是我的android请求代码,还有wireshark日志: try { url = new URL(path_url + apiMsg); //in the real code, there is an ip and a port con

我在android应用程序中使用HttpURLConnection使用API,运行正常,但如果我收到响应代码,但200 ok(如404500)除外,则当我在错误响应代码后点击下一个请求时,我的端口正在更改: 下面是我的android请求代码,还有wireshark日志:

try {
            url = new URL(path_url + apiMsg); //in the real code, there is an ip and a port

            conn = (HttpURLConnection) url.openConnection();

            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept","*/*");

}
请参阅wireshark日志:


因此,如何避免错误场景中的端口更改以及success 200案例中的端口更改,以便我们继续在同一个端口上运行。

阅读HttpURLConnection源代码中的sun.net.http.errorstream.enableBuffering

默认情况下,当响应代码>=400时,连接关闭。 这是一种处理错误流的干净但不是很有效的方法

与其设置晦涩的系统属性来处理这个问题,不如使用合适的http客户机,比如apache