【问题标题】:java how to receive web service response in JSONjava如何在JSON中接收Web服务响应
【发布时间】:2017-08-06 08:47:28
【问题描述】:

我是 web 服务的新手,我正在调用一个 web 服务,它应该返回带有以下代码的 JSON - 问题是我得到的是 xml 格式的响应 当我使用 google rest api 尝试相同的参数时 - 响应在 JSON 中 任何想法我做错了什么?

 public static  String getSFData(String urlSuffix) throws MalformedURLException, ProtocolException , IOException    
 {


    String header = "Basic XXXXX";
    URL url = new URL("https://api2.successfactors.eu/odata/v2/"+urlSuffix);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    connection.setRequestMethod("GET");
    connection.setRequestProperty("authorization",header);
    connection.setRequestProperty("Content-Type", "application/json");


    BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuffer stringBuffer = new StringBuffer();
    String line;
    while ((line = bf.readLine()) != null )
    {
        stringBuffer.append(line);
    }
    String response = stringBuffer.toString();
    System.out.println("response"+response);
    return response;

 }

【问题讨论】:

  • Content-Type 指定您要发送的内容类型,并且您不发送任何内容(您也不应该使用GET)。要指定所需的 response 内容类型,请改为设置 Accept 标头值。
  • 你能告诉我怎么做吗?我不明白
  • 正如我所说,设置Accept 标头值而不是,即将"Content-Type" 替换为"Accept"
  • 知道了!!我添加了 connection.setRequestProperty("Accept", "application/json");解决了我的问题 - 谢谢安德烈亚斯!!

标签: java json web-services


【解决方案1】:

更新

您可以尝试使用http://api2.successfactors.eu/odata/v2/User? $format=json 之类的 API URL 来获取 JSON 格式的数据。

使用StringBuilder 而不是StringBuffer

设置内容类型后尝试以下操作。

    connection.connect();

    int status = connection.getResponseCode();

    switch (status) {
        case 200:
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            String response = stringBuilder.toString();
            System.out.println("response : " + response);
    }

【讨论】:

  • 谢谢 - 但这无济于事 - 响应在 xml 中,我需要它在 json 中
  • 所以,可能你必须将 XML 映射到 JAVA 对象,然后你可以将它转换为 json。
  • @RahavMagen 在文档中我发现 API URL 中的 $format=json 可以获取 JSON 格式的数据。你试试这个。查看我的更新答案
  • 是的,你是对的 - 它也在解决它 - 我添加了 ?$format=json 并且它有所帮助,但我实际上使用了安德里亚建议的 connection.setRequestProperty("Accept", "application/json") ;也解决了我的问题 - 感谢您的帮助(我没有足够的声誉来更新分数)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-13
  • 2012-07-17
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多