java如何在JSON中接收Web服务响应

时间:2017-08-06 08:47:28

标签: java json web-services

我是Web服务的新手,我正在调用一个Web服务,该服务应该返回带有folliwng代码的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;

 }

1 个答案:

答案 0 :(得分:1)

<强>更新

您可以尝试使用http://api2.successfactors.eu/odata/v2/User? $format=json之类的API网址来获取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);
    }