• 【工具】Java请求带http重定向的地址 自动进行重定向


    【工具】Java请求带http重定向的地址 自动进行重定向

    1. import java.io.BufferedReader;
    2. import java.io.IOException;
    3. import java.io.InputStreamReader;
    4. import java.net.HttpURLConnection;
    5. import java.net.URL;
    6. public class HTTPGETWithMultipleHeaders {
    7. public static void main(String[] args) {
    8. try {
    9. String urlToRead = "http://example.com"; // 你要请求的URL
    10. while (urlToRead != null) {
    11. URL url = new URL(urlToRead);
    12. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    13. connection.setRequestMethod("GET"); // 使用GET请求方式
    14. // 设置多个自定义请求头
    15. connection.setRequestProperty("User-Agent", "YourUserAgent");
    16. connection.setRequestProperty("Authorization", "Bearer YourAccessToken");
    17. connection.setRequestProperty("Custom-Header", "CustomValue");
    18. int responseCode = connection.getResponseCode();
    19. if (responseCode == HttpURLConnection.HTTP_OK) {
    20. // 请求成功,读取响应内容
    21. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    22. String line;
    23. while ((line = reader.readLine()) != null) {
    24. System.out.println(line);
    25. }
    26. reader.close();
    27. break; // 响应成功,不再重定向
    28. } else if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
    29. // 处理重定向
    30. String newUrl = connection.getHeaderField("Location");
    31. if (newUrl != null) {
    32. urlToRead = newUrl;
    33. } else {
    34. System.out.println("重定向地址未找到。");
    35. break;
    36. }
    37. } else {
    38. System.out.println("HTTP请求失败,响应代码: " + responseCode);
    39. break;
    40. }
    41. }
    42. } catch (IOException e) {
    43. e.printStackTrace();
    44. }
    45. }
    46. }

  • 相关阅读:
    移动跨平台开发跨家选型参考建议
    一个快速切换一个底层实现的思路分享
    Git获取本地仓库及基础操作指令
    python--连接oracle数据库
    七通道NPN 达林顿管GC2003,专为符合标准 TTL 而制造,最高工作电压 50V,耐压 80V
    MCS:离散随机变量——Pascal分布
    挖矿病毒消灭记二
    第十七章 Python编程
    swagger 依赖及应用
    Spring - InstantiationAwareBeanPostProcessor 扩展接口
  • 原文地址:https://blog.csdn.net/G971005287W/article/details/134011410