如何处理503响应代码java.net

如何处理503响应代码java.net,java,networking,Java,Networking,以下是在java网络中处理503响应代码的合适方法吗?这段代码——特别是对disconnect和null的调用——做了什么 URL url = new URL(some url); HttpURLConnection h =(HttpURLConnection)url.openConnection(); int x = h.getResponseCode(); while(x==503) { h.disconnect(); h = null; h =(HttpURLCon

以下是在java网络中处理503响应代码的合适方法吗?这段代码——特别是对disconnect和null的调用——做了什么

URL url = new URL(some url);
HttpURLConnection h =(HttpURLConnection)url.openConnection();
int x = h.getResponseCode();
while(x==503)
{
    h.disconnect();
    h = null;
    h =(HttpURLConnection)url.openConnection();
    x = h.getResponseCode();
}
disconnect()关闭底层TCP套接字

URL url = new URL(some url);
HttpURLConnection h =(HttpURLConnection)url.openConnection();
int x = h.getResponseCode();
while(x==503)
{
    h.disconnect();
    h = null;
    h =(HttpURLConnection)url.openConnection();
    x = h.getResponseCode();
}
在重新分配局部变量之前,立即将其设置为null不会产生任何效果

URL url = new URL(some url);
HttpURLConnection h =(HttpURLConnection)url.openConnection();
int x = h.getResponseCode();
while(x==503)
{
    h.disconnect();
    h = null;
    h =(HttpURLConnection)url.openConnection();
    x = h.getResponseCode();
}

在这个循环中应该有一个睡眠,每次失败的间隔都会增加,重试次数有限

无论你想让它做什么都是合适的方式。为了使某件事情安全可靠,最好在成功之前重复,而不是只处理503场景

URL url = new URL(some url);
HttpURLConnection h =(HttpURLConnection)url.openConnection();
int x = h.getResponseCode();
while(x==503)
{
    h.disconnect();
    h = null;
    h =(HttpURLConnection)url.openConnection();
    x = h.getResponseCode();
}
最简单的示例:循环直到返回200(成功)代码

URL url = new URL(some url);
HttpURLConnection h =(HttpURLConnection)url.openConnection();
int x = h.getResponseCode();
while(x==503)
{
    h.disconnect();
    h = null;
    h =(HttpURLConnection)url.openConnection();
    x = h.getResponseCode();
}

(最好将其抽象为方法和类,并在可能的情况下使用OOP和单元测试。)

-1从一般观点来看,这是一个非常糟糕的想法。例如:无论您发出多少请求,3XX响应代码(重定向)都不太可能不同。4XX代码(错误请求/未经授权)或501(未实施)同样不太可能更改(直到实施).事实上,看一下,你会发现实际上很少有代码是非永久性的。如果你想保持对HTTP协议的一些普遍遵守,你需要更精细的错误处理。我同意,我并不是在提倡这是一种正确的方法,只是指出为503之类的东西添加“hacks”并不是真正意义上的在应用程序如何工作的“大图”中。
URL url = new URL(some url);
HttpURLConnection h =(HttpURLConnection)url.openConnection();
int x = h.getResponseCode();
while(x==503)
{
    h.disconnect();
    h = null;
    h =(HttpURLConnection)url.openConnection();
    x = h.getResponseCode();
}