我正在编写Java类来访问第三方公共REST API Web服务,该服务使用特定的APIKey参数进行保护。
当我将json输出本地保存到文件中时,可以使用JsonNode API访问所需的Json数组。
例如
JsonNode root = mapper.readTree(new File("/home/op/Test/jsondata/loans.json"));
但是,如果我尝试将实时安全的Web URL与JsonNode一起使用
例如
JsonNode root = mapper.readTree(url);
我得到一个:
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60))
这表明我的类型不匹配。但我认为这很可能是连接问题。
我正在处理与REST服务的连接:
private static String surl = "https://api.rest.service.com/xxxx/v1/users/xxxxx/loans?apikey=xxxx"
public static void main(String[] args) {
try {
URL url = new URL(surl);
JsonNode root = mapper.readTree(url);
....
}
我也尝试使用:
URL url = new URL(surl);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
InputStream isr = httpcon.getInputStream();
JsonNode root = mapper.readTree(isr);
具有相同的结果。
当我删除APIKey时,会收到状态400错误。因此,我认为我一定不能处理APIKey参数。
是否可以使用JsonNode处理对安全的REST服务URL的调用?我想继续使用JsonNode API,因为我只提取了两个键:在大型数组中遍历多个对象的值对。
答案 0 :(得分:1)
只需尝试简单地将响应读入字符串并将其记录下来,以查看实际发生的情况以及为什么不从服务器接收JSON。
URL url = new URL(surl);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
InputStream isr = httpcon.getInputStream();
try (BufferedReader bw = new BufferedReader(new InputStreamReader(isr, "utf-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = bw.readLine()) != null) { // read whole response
sb.append(line);
}
System.out.println(sb); //Output whole response into console or use logger of your choice instead of System.out.println
}