java获取301 302的跳转网址

访问a链接会302到b链接,现在我想得到b链接。
现在需要一个java方法,传入a参数,方法返回b链接。
在网上找了很多案例发现取不到,有一个取出来就是500错误。
希望有人能帮我搞下,58元。禁止chatgpt ai等非人工回答。最好能私信我

//执行结果:我返回了500错误,如下控制台输出所示:
getjurl:code=500,html=500 Internal Server Error HTTP/1.1
realurl=
退出代码:111
//测试类或启动函数
//这是我具体测试的网址,它打开后通过F12网络,可以看到发送了一个302跳转至百度网盘页面。我的目的是获取该跳转后的链接。若该网址打开显示“环境异常”,则为您必须使用电脑PC设备才能访问该链接。
   String realurl=getjurl("https://sytaolu.com/wp-content/themes/zibll/zibpay/download.php?post_id=63128&key=2c2140d14b&down_id=0");
        System.out.println("realurl="+realurl);
        System.exit(111);

//具体方法getjurl
//注意此方法需要引入pom依赖:
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
        <dependency>
            <groupId>org.apache.httpcomponents.client5</groupId>
            <artifactId>httpclient5</artifactId>
            <version>5.2.1</version>
        </dependency>

public static String getjurl(String url) throws IOException {
        System.out.println("getjurl="+url);
        //设置不允许重定向
        RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();

        //使用 CloseableHttpClient 而非 HttpClient
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
        httpGet.addHeader("Accept-Charset","UTF-8");
        httpGet.addHeader("Content-Type","text/html");
        httpGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;");

        HttpResponse response = httpClient.execute(httpGet);

        int code =response.getCode();
        System.out.println("getjurl:code="+code+",html="+ response.toString());
        String newuri="";
        if (code == 302 || code==301) {
            Header header = response.getFirstHeader("location"); // 跳转的目标地址是在response的 HTTP-HEAD 中的,location的值
            newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。
        }
        return newuri;
    }

于是,我用最简单的方式,结果返回null


 // 定义一个方法,传入a参数,返回b链接
    private static String getRedirectUrl(String a) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(a).openConnection(); // 创建连接对象
        conn.setInstanceFollowRedirects(false); // 设置不允许重定向
        conn.setConnectTimeout(5000); // 设置连接超时时间
        return conn.getHeaderField("Location"); // 返回响应头中的Location字段值,即b链接
    }

500错误代码贴出来

给你个例子参考一下

import java.net.HttpURLConnection;
import java.net.URL;

public class GetRedirectUrl {
    public static void main(String[] args) throws Exception {
        String a = "http://www.baidu.com/link?url=ByBJLpHsj5nXx6DESXbmMjIrU5W4Eh0yg5wCQpe3kCQMlJK_RJBmdEYGm0DDTCoTDGaz7rH80gxjvtvoqJuYxK"; // a链接
        String b = getRedirectUrl(a); // 调用方法获取b链接
        System.out.println(b); // 打印b链接
    }

    // 定义一个方法,传入a参数,返回b链接
    private static String getRedirectUrl(String a) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(a).openConnection(); // 创建连接对象
        conn.setInstanceFollowRedirects(false); // 设置不允许重定向
        conn.setConnectTimeout(5000); // 设置连接超时时间
        return conn.getHeaderField("Location"); // 返回响应头中的Location字段值,即b链接
    }
}

try{
    URL url = new URL("https://www.baidu.com/");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.connect();
    System.out.println("code=" + connection.getResponseCode());
    String redirectUrl = connection.getHeaderField("Location");
    connection.disconnect();
    System.out.println(redirectUrl);
} catch(Exception e) {
    e.printStackTrace();
}

你可以使用Java的java.net.HttpURLConnection类或者更高级的库如Apache HttpClient或者OkHttp来获取HTTP响应中的重定向URL。

以下是使用HttpURLConnection的示例:

import java.net.HttpURLConnection;  
import java.net.URL;  
  
public class Main {  
    public static void main(String[] args) throws Exception {  
        URL url = new URL("http://example.com"); // 替换为你的URL  
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();  
        httpURLConnection.setRequestMethod("GET");  
        httpURLConnection.connect();  
  
        String redirectedUrl = httpURLConnection.getHeaderField("Location"); // 获取重定向URL  
        System.out.println(redirectedUrl);  
    }  
}

注意,这个方法只能获取到HTTP响应中的"Location"头,它提供重定向URL的信息。但这个方法可能无法处理某些复杂的重定向情况,例如带有查询参数的重定向。对于更复杂的HTTP通信,你可能需要使用更强大的库,如Apache HttpClient或OkHttp。

b链接在a链接的响应头location里面

可以尝试使用以下方法来获取b链接:

  1. 使用HttpURLConnection类发送HTTP请求,并设置followRedirects属性为true,以便自动跟随重定向。然后获取响应头中的Location字段,即为b链接。
  2. 如果第一种方法无效,你可以尝试使用HttpClient库来发送HTTP请求,并使用setRedirectStrategy方法将重定向策略设置为LaxRedirectStrategy。然后获取响应头中的Location字段,即为b链接。

希望以上信息对您有所帮助。如有其他问题,请随时告知😊😊😊

关于获取301和302跳转网址的示例代码:

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        try {
            String a = "https://sytaolu.com/wp-content/themes/zibll/zibpay/download.php?post_id=63128&key=2c2140d14b&down_id=0";
            String b = getRedirectUrl(a);
            System.out.println(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getRedirectUrl(String a) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(a).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setConnectTimeout(5000);
        return conn.getHeaderField("Location");
    }
}

请确保您的网络连接正常以及所需的依赖已正确导入。这段代码会发送HTTP请求并获取跳转后的链接,如果是301或302跳转,返回的就是目标链接(b链接)。

基于你的代码修改了一下 你试试

```java

import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class Main {
public static void main(String[] args) {
try {
String realurl = getRedirectUrl("https://sytaolu.com/wp-content/themes/zibll/zibpay/download.php?post_id=63128&key=2c2140d14b&down_id=0%22);
System.out.println("realurl=" + realurl);
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getRedirectUrl(String url) throws IOException {
    RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();

    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
    httpGet.addHeader("Accept-Charset", "UTF-8");
    httpGet.addHeader("Content-Type", "text/html");
    httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;");

    HttpResponse response = httpClient.execute(httpGet);

    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println("getRedirectUrl: code=" + statusCode);

    String newUrl = "";
    if (statusCode == 302 || statusCode == 301) {
        Header header = response.getFirstHeader("location");
        newUrl = header.getValue();
    }

    return newUrl;
}

}
``


import java.net.HttpURLConnection;  
import java.net.URL;  
public class Main {  
    public static void main(String[] args) throws Exception {  
        URL url = new URL("http://example.com"); // 替换为你的URL  
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();  
        httpURLConnection.setRequestMethod("GET");  
        httpURLConnection.connect();  
        String redirectedUrl = httpURLConnection.getHeaderField("Location"); // 获取重定向URL  
        System.out.println(redirectedUrl);  
    }  
}

500是服务端错误,请把报错日志贴出来

【以下回答由 GPT 生成】

我可以帮助你解决这个问题。你可以使用Java的HttpURLConnection类来获取301和302重定向后的目标网址。以下是一个示例代码来演示如何实现:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class RedirectUrlGetter {

    public static String getRedirectUrl(String urlStr) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(false); // 禁止自动重定向
            connection.connect();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                String redirectUrl = connection.getHeaderField("Location");
                if (redirectUrl != null) {
                    return redirectUrl;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ""; // 如果未能获取到重定向目标网址,返回空字符串
    }

    public static void main(String[] args) {
        String originalUrl = "http://example.com"; // 输入你想要获取重定向目标的原始网址
        String redirectUrl = getRedirectUrl(originalUrl);
        if (!redirectUrl.isEmpty()) {
            System.out.println("Redirect URL: " + redirectUrl);
        } else {
            System.out.println("Failed to get redirect URL.");
        }
    }
}

这个例子中,我们首先创建一个URL对象,并打开一个HttpURLConnection连接。然后,我们禁止自动重定向,通过调用setInstanceFollowRedirects(false)方法。接下来,我们发送请求并获取响应的状态码。如果状态码是301或302,我们从响应的头部获取"Location"字段的值,该字段包含了重定向后的目标网址。最后,我们将目标网址返回或者打印出来。

请注意,这段代码只能处理单层的重定向,如果遇到多层的重定向,你可能需要在代码中添加循环来跟踪每个重定向的位置。

希望这可以帮助到你,如果你有任何问题,请随时提问。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^