Java API 请求错误修复:构建正确 URL 获取响应

在使用 Java 进行 API 请求时,构建正确的 URL 至关重要。本文将重点介绍一个常见的错误:构建 API 请求 URL 时出现错误,导致无法获取到正确的响应。

问题代码:

try {
    // 构建API请求URL
    //api.qingyunke.com/api.php?key=free&appid=0&msg=' + URLEncoder.encode(message, 'UTF-8');

    // 发送GET请求给API,并获取响应
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod('GET');

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    reader.close();

    return response.toString();
}  

错误分析:

代码中没有正确构建 API 请求的 URL。应该在 URL 前添加 http://https://,并且需要将 URL 中的变量 message 进行 URL 编码。

解决方案:

使用以下代码替换原来的代码:

try {
    // 构建API请求URL
    String url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=' + URLEncoder.encode(message, 'UTF-8');

    // 发送GET请求给API,并获取响应
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod('GET');

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    reader.close();

    return response.toString();
} catch (Exception e) {
    e.printStackTrace();
}

修改后的代码:

  • 将 URL 前添加 http://,确保 URL 正确。
  • 使用 URLEncoder.encode(message, 'UTF-8')message 进行 URL 编码,避免特殊字符导致的错误。

通过以上修改,可以确保代码能够正确构建 API 请求的 URL 并获取响应。

总结:

构建正确的 API 请求 URL 是进行 API 请求的关键一步。在编写代码时,要注意 URL 中的协议、域名、路径和参数,并对参数进行 URL 编码,避免出现错误。

Java API 请求错误修复:构建正确 URL 获取响应

原文地址: https://www.cveoy.top/t/topic/cF8F 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录