400使用Java客户端从OData服务响应

时间:2015-01-29 22:32:47

标签: java odata

www.odata.org网站演示了如何在6个步骤中使用OData服务。我坚持直接在主页上的示例的第3步。我故意只使用标准的Java 7库。以下代码产生400响应。我已使用Chrome中的Advanced Rest Client尝试使用同一查询来验证网址是否正确。

有人可以告诉我如何仅使用标准Java 7库成功完成第3步吗?

URL url = new URL("http://services.odata.org/V4/TripPinServiceRW/People?$top=2&$filter=Trips/any(d:d/Budget gt 3000)");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestProperty("accept", "application/json");
c.setRequestProperty("Content-Type", "application/json");
c.setRequestMethod("GET");

BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));

String input;
StringBuilder sb = new StringBuilder();
while ((input = in.readLine()) != null) {
    sb.append(input);
}
in.close();

System.out.println(sb);

2 个答案:

答案 0 :(得分:0)

尝试将c.getInputStream()更改为c.getOutputStream():

BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));

- >

BufferedReader in = new BufferedReader(new InputStreamReader(c.getOutputStream()));

顺便说一下,如果你想创建一个用于使用OData服务的java客户端,我会推荐Apache Olingo java客户端。 @ https://git-wip-us.apache.org/repos/asf?p=olingo-odata4.git;a=blob;f=fit/src/test/java/org/apache/olingo/fit/proxy/v4/EntitySetTestITCase.java;h=ccf956d4fc818ee0545a28bf8f6d8b3461b7da5c;hb=HEAD,它是一个测试案例,显示查询OData服务是多么容易:

for (Customer customer : container.getCustomers()) 
{ 
  assertNotNull(customer);  
  count++;  
}

答案 1 :(得分:0)

您需要在网址上对空格进行编码,如下所示:URL url = new URL("http://services.odata.org/V4/TripPinServiceRW/People?$top=2&$filter=Trips/any(d:d/Budget%20gt%203000)");

这是工作代码:

URL url = new URL("http://services.odata.org/V4/TripPinServiceRW/People?$top=2&$filter=Trips/any(d:d/Budget gt 3000)");
URL urlToEncode = new URL(url);
URI uri = new URI(urlToEncode.getProtocol(), urlToEncode.getUserInfo(), urlToEncode.getHost(), urlToEncode.getPort(), urlToEncode.getPath(), urlToEncode.getQuery(), urlToEncode.getRef());

HttpURLConnection c = (HttpURLConnection) uri.toURL().openConnection();
c.setRequestProperty("accept", "application/json");
c.setRequestMethod("GET");

BufferedReader in = new BufferedReader(newInputStreamReader(c.getInputStream()));

查看更多here