0

我创建了一个类,它提供了一种通过 REST 获取 JSON 对象的方法,该对象应该被反序列化为 LinkedHashMap。方法如下:

 @Override
public LinkedHashMap refreshStatus(String metricType, String metricPeriod) {
    ObjectMapper mapper = new ObjectMapper();
    LinkedHashMap<String,String> map = null;

     try {
        map = mapper.readValue(new File("http://localhost:8081/Metrics/Stats/JSONP/ReceiveData/"+metricType+"/"+metricPeriod+"/?callback="), LinkedHashMap.class);


    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
}
    return map;
}

当我在浏览器中输入带有一些特定参数的 URL 时,即

http://localhost:8081/Metrics/Stats/JSONP/ReceiveData/Totals/All/?callback=

我得到了一个正确的 JSON 对象:

{"Boxes":"8","Contracts":"23","Updates":"1","Deactivations":"4","ActiveBoxes":"33","InactiveBoxes":"1","PendingInstallationsContracts":"70","Alerts":"626","PercentsBoxInstalled":"100.0%","Miles":"0"}

但是,当我运行应用程序并调用该方法时,我得到了 FileNotFoudException:

java.io.FileNotFoundException: http:/localhost:8081/Metrics/Stats/JSONP/ReceiveData/Totals/All/?callback= (No such file or directory)

有谁知道问题可能出在哪里?提前致谢!

4

1 回答 1

2

该文件确实无法在您的计算机上找到。您尝试在本地文件系统中创建与真实文件相对应的文件对象,并提供 URL 作为参数而不是文件系统路径。

您实际上想要执行 HTTP GET,即执行以下操作。

urlString = "http://localhost:8081/Metrics/Stats/JSONP/ReceiveData/Totals/All/?callback=";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
map = mapper.readValueconn.getInputStream(); 
于 2013-09-30T15:05:54.497 回答