如何使用HttpURLConnection携带查询参数发起PUT请求?
解决HttpURLConnection调用第三方API时的路由找不到问题
兄弟,我帮你捋捋这个问题——你遇到的The REST API Url could not be found in the mappings registry错误,核心原因是实际请求的URL不符合第三方API的路由规则,咱们从几个常见的坑入手排查:
1. 先干掉URL开头的空格!
看你代码里的URL:" http://thirdparty.com/party/api/v2/ksp/12/ks"——开头多了个空格!这会导致服务器解析到的URL是带空格的,绝对不在它的路由映射表里,直接把空格删掉,改成:
url = new URL("http://thirdparty.com/party/api/v2/ksp/12/ks");
2. 正确传递查询参数(别硬拼!)
如果要加查询参数,直接硬拼容易出现编码错误(比如参数里有空格、特殊字符),导致URL格式无效。推荐两种规范的方式:
方式一:用URLEncoder编码参数
// 基础URL(无空格) String baseUrl = "http://thirdparty.com/party/api/v2/ksp/12/ks"; // 编码参数,避免特殊字符问题 String paramValue = URLEncoder.encode("你的参数值", StandardCharsets.UTF_8); // 拼接成完整URL String fullUrl = baseUrl + "?paramName=" + paramValue; URL url = new URL(fullUrl);
方式二:用URI类构建更规范的URL
这种方式会自动处理编码和格式问题,更稳妥:
URI uri = new URI( "http", "thirdparty.com", "/party/api/v2/ksp/12/ks", "param1=值1¶m2=值2", // 查询参数部分 null ); URL url = uri.toURL();
3. 核对第三方API的路由规则
有时候你以为的查询参数,第三方可能要求是路径参数。比如如果API文档里要求的是/ksp/{id}/ks/{param},那你就不能把参数放在?后面,得嵌入到路径里。一定要再仔细看一遍第三方的API文档,确认参数的位置是路径参数还是查询参数。
4. 检查请求方法和头信息
如果第三方API要求用POST方法,而你默认用了GET,或者缺少必要的请求头(比如Content-Type: application/json),也可能导致路由匹配失败。比如如果是POST请求,要记得设置:
connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); // 写入请求体(如果需要的话) OutputStream os = connection.getOutputStream(); os.write("请求体内容".getBytes(StandardCharsets.UTF_8)); os.flush(); os.close();
修正后的完整代码示例
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; public class ThirdPartyApiCall { public static void main(String[] args) { StringBuffer response = new StringBuffer(); try { // 1. 基础URL(无空格) String baseUrl = "http://thirdparty.com/party/api/v2/ksp/12/ks"; // 2. 编码查询参数 String param1 = URLEncoder.encode("your_first_param", StandardCharsets.UTF_8); String param2 = URLEncoder.encode("your_second_param", StandardCharsets.UTF_8); String fullUrl = baseUrl + "?param1=" + param1 + "¶m2=" + param2; URL url = new URL(fullUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法(根据API要求调整) connection.setRequestMethod("GET"); // 添加必要的请求头 connection.setRequestProperty("Accept", "application/json"); // 读取响应 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); connection.disconnect(); System.out.println("API Response: " + response.toString()); } catch (Exception e) { e.printStackTrace(); } } }
如果以上都试过还是不行,建议抓包看下实际发送的请求URL是什么,和API文档里的正确URL对比,就能快速找到差异了。
内容的提问来源于stack exchange,提问作者N00b Pr0grammer
相关产品推荐
相关产品推荐

