プロキシを使用してサーバーから情報を取得する次の方法があります。時には劣悪なプロキシに私はあなたが私の方法で見ることができるように私はすでにサーバが何かを返した場合、私は、サーバーの応答の内容を取得するためにそれを行う必要がありcatch (IOException ioe)
を使用していますSocketException
、SSLException
、SSLHandshakeException
またはConnectException
いくつかの例外について再試行メソッド
を取得します上記の例外が発生した場合、どうすればメソッドを再試行できますか?
public String getMeta() throws IOException
{
HttpsURLConnection con = null;
InputStream is = null;
StringWriter writer = new StringWriter();
try
{
String url = "https://api.myapp.com/meta";
URL urlObj = new URL(url);
if (useProxy && fullProxy)
{
myapp.Proxy proxyCustom = getRandomProxy();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyCustom.getProxyIp(), proxyCustom.getProxyPort()));
con = (HttpsURLConnection) urlObj.openConnection(proxy);
}
else
{
con = (HttpsURLConnection) urlObj.openConnection();
}
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setRequestProperty("host", urlObj.getHost());
con.setRequestProperty("Connection", "Keep-Alive");
int responseCode = 0;
responseCode = con.getResponseCode();
is = con.getInputStream();
writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
}
catch (IOException ioe)
{
if (con instanceof HttpsURLConnection)
{
HttpsURLConnection httpConn = (HttpsURLConnection) con;
int statusCode = httpConn.getResponseCode();
if (statusCode != 200)
{
is = httpConn.getErrorStream();
writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return writer.toString();
}
ループまたは再帰を使用します。あなたがそのようなものや無限の再帰/ループを避けたいのであれば、余分なロジックを必要とせずにtryブロックから新しいメソッドにすべてを入れてください。その後、別の時間を呼び出すことができます。 – HopefullyHelpful
'メソッドを再試行するにはどうすればいいですか'一度だけ再試行しますか、例外がスローされなくなるまで継続的に再試行しますか? – copeg
@copeg再試行する必要のある回数を設定する簡単な方法があることを願っていますが、複雑すぎるため、一度試してみるだけです。 – Arya