• 【工具】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. }

  • 相关阅读:
    Xintell——全生命周期的模型建设+智能数据中台
    结合element的el-tooltip实现文本溢出进行省略,鼠标移入显示全部
    生产服务器变卡怎么排查
    MARL值分解方法总结(1)
    单调栈总结
    TypeORM 框架
    Feign源码解析:初始化过程(一)
    【机器学习】线性回归【下】正则化最小二乘估计
    你知道吗?小程序组件≠小程序插件
    商品管理系统数据库设计--SQL Server
  • 原文地址:https://blog.csdn.net/G971005287W/article/details/134011410