0

我正在使用以下代码通过基本身份验证调用 Assembla REST Api。我得到 html 输出而不是 xml。我想在我的程序中使用这个输出数据,但无法从 html 格式中获取它。请建议如何以 xml 格式获取输出。

    HttpURLConnection conn = null;     
    String authentication = "username:password";
    String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
    URL url = new URL("https://www.assembla.com/spaces/my_spaces");
    //URL url = new URL("https://www.assembla.com/");
     conn = (HttpURLConnection) url.openConnection();
     conn.setRequestMethod("GET");
     conn.setRequestProperty("Content-Type","Accept: application/xml; charset=utf-8");
     conn.setRequestProperty("Authorization", "Basic " + encoding);
     conn.setDoOutput(true);
     conn.connect();

    System.out.println(conn.getResponseCode()); 
    System.out.println(conn.getResponseMessage());

    InputStreamReader isr =
        new InputStreamReader(conn.getInputStream());
    BufferedReader br = new BufferedReader(isr);

    String inputLine;

    while ((inputLine = br.readLine()) != null)
        System.out.println(inputLine);

    br.close();

我也尝试将此输出转换为 jsonObject 但收到错误 org.json.JSONException:Value

    InputStreamReader isr =
            new InputStreamReader(conn.getInputStream());
    BufferedReader br = new BufferedReader(isr);

    StringBuilder sb = new StringBuilder();

    String inputLine;


        while ((inputLine = br.readLine()) != null){
            System.out.println(inputLine);
            sb.append(inputLine);
        }   

        try {
            JSONObject user = new JSONObject(sb.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
4

1 回答 1

0

只需更改 - conn.setRequestProperty("Content-Type","Accept: application/xml; charset=utf-8"); 到 conn.setRequestProperty("Accept", "text/xml"); 那时它会正常工作。

于 2011-08-19T13:26:32.277 回答