You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java获取Pastebin raw原始内容时返回空行的问题如何解决?

Pastebin空响应问题定位与修复方案

问题定位步骤

  • 校验HTTP响应状态:当前代码未判断响应状态直接读取内容,若Pastebin返回3xx重定向、4xx客户端错误(如403反爬拦截、404无效pasteKey)、5xx服务端错误,都会返回空或非预期内容。可先通过如下代码打印响应状态和头信息排查:
URL url = new URL("http://pastebin.com/raw.php?i="+pasteKey);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 打印状态码判断响应是否正常
System.out.println("响应状态码:" + conn.getResponseCode());
// 打印响应头确认返回内容类型
System.out.println("Content-Type:" + conn.getHeaderField("Content-Type"));
  • 检查反爬拦截:Java默认请求的User-Agent携带Java/版本号标识,Pastebin的反爬策略会直接拦截这类请求,返回空内容。
  • 确认paste权限:校验pasteKey对应内容为公开状态,未过期、未删除,私有paste需携带官方API密钥才能访问。

修复方案

修复后完整代码

try {
    String pasteKey = "替换为实际pasteKey";
    // 优先用官方推荐的HTTPS raw路径,兼容性更好
    URL url = new URL("https://pastebin.com/raw/" + pasteKey);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // 模拟浏览器请求头绕过反爬拦截
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
    // 自动跟进3xx重定向
    conn.setInstanceFollowRedirects(true);
    conn.setRequestMethod("GET");
    int responseCode = conn.getResponseCode();
    // 2xx状态码读正常流,异常状态读错误流排查问题
    InputStream inputStream = (responseCode >= 200 && responseCode < 300) ? conn.getInputStream() : conn.getErrorStream();
    String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
            .lines()
            .collect(Collectors.joining("\n"));
    System.out.println("返回内容:\n" + text);
    inputStream.close();
    conn.disconnect();
} catch (IOException e) {
    e.printStackTrace();
}

额外注意事项

  • 若请求频率过高被临时封禁,可降低请求频率,或申请Pastebin开发者API密钥调用官方接口,请求限制更宽松
  • 私有内容必须携带对应API认证参数才能获取,无法直接通过raw路径请求

内容的提问来源于stack exchange,提问作者KZB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:18:01