Java Http重定向

时间:2016-05-27 13:35:44

标签: java http

我使用此代码发送POST Http请求:

String url1 = "URL1";
String url2 = "URL2";   
URL obj = new URL(url1);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
this.setHeader(con,urlParameters.length());
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

如果URL1关闭,如何重定向到URL2?

2 个答案:

答案 0 :(得分:0)

如果无法建立连接,

obj.openConnection()应该抛出异常。我假设你的函数抛出了这个异常。相反,你可以抓住它,然后再试一次。请注意,从连接写入和读取也会引发异常。考虑如何处理它们(再试一次,或者抛出来让调用者处理问题)

URL obj;
HttpsURLConnection con = null;
try
{
    obj = new URL(url1);
    con = (HttpsURLConnection) obj.openConnection();
}
catch(Exception e)
{
    System.out.println("Error, redirecting to url 2");
    e.printStackTrace();

    try
    {
        obj = new URL(url2);
        con = (HttpsURLConnection) obj.openConnection();
    }
    catch(Exception e)
    {
         System.out.println("Error, url2 failed");
         throw e;  // This will make your function throw an exception when both urls are down.
    }
}

答案 1 :(得分:0)

尝试使用此代码发布并重新构建它以满足您的需求。 post data in java console application

    URL serverUrl =
            new URL("http://localhost:1611/POST/othersite.aspx");
    HttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    Boolean isUrl1Down=false;
    try {
        BufferedWriter httpRequestBodyWriter = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
        httpRequestBodyWriter.write("userName=Johnny+Jacobs&password=1234");
        httpRequestBodyWriter.close();
    }catch (IOException ie){
        isUrl1Down=true;
    }
    if(isUrl1Down){
        System.out.println("Try with secound URL");
    }
    // Reading from the HTTP response body
    Scanner httpResponseScanner = new Scanner(urlConnection.getInputStream());
    while(httpResponseScanner.hasNextLine()) {
        System.out.println(httpResponseScanner.nextLine());
    }
    httpResponseScanner.close();