解析 Java 中的 HttpResponse JSON

Parsing a HttpResponse JSON in Java

我正在尝试向 Web API 发出 HTTP post 请求,然后解析接收到的 HttpResponse 并访问正文中的键值对。我的代码是这样的:

public class access {

// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {


    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("https://XXXXXXX/RSAM_API/api/Logon");

// Request parameters and other properties.
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(2);
    urlParameters.add(new BasicNameValuePair("UserId", "XXXXX"));
    urlParameters.add(new BasicNameValuePair("Password", "XXXXXX"));
    try {
       httppost.setEntity(new UrlEncodedFormEntity(urlParameters));


//Execute and get the response.
       HttpResponse response = httpclient.execute(httppost);

       BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
       String line;
       while(null !=(line=rd.readLine())){

           System.out.println(line);
       }
       System.out.println(response);

       String resp = EntityUtils.toString(response.getEntity());
       JSONObject obj = new JSONObject(resp);

   }
   catch (Exception e){

       e.printStackTrace();
   }

}

}

我试图通过使用以下两行代码将其转换为 JSONObject 来访问正文:

String resp = EntityUtils.toString(response.getEntity());
           JSONObject obj = new JSONObject(resp);

但是我在第二行中收到错误消息:

JSONObject
(java.util.Map)
in JSONObject cannot be applied
to
(java.lang.String)

不确定这是否是正确的方法。有没有办法做我想做的事?

任何帮助将不胜感激,谢谢。

编辑: 因此,当我尝试使用以下行打印响应正文时, String resp = EntityUtils.toString(response.getEntity()); System.out.println(resp);

我得到结果:{"APIKey":"xxxxxxxxxxxxxx","StatusCode":0,"StatusMessage":"Y‌​ou have been successfully logged in."}

我正在寻找一种方法来解析这个结果,然后访问每个元素。有办法吗?

尝试以下行来解析 JSON:

JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(resp);

如果 JSON 无效,以上行将使 JSON 生效并通过异常。

您不需要阅读额外 while 循环中的响应。 EntityUtils.toString(response.getEntity());会为你做这件事。正如您之前阅读响应流一样,在到达 response.getEntity().

时流已经关闭

根据 JsonSimple 的 JsonObject 文档,它在构造函数中采用映射而不是字符串。所以你得到它所说的错误。 您应该先使用 JSONParser 来解析字符串。 最好将编码作为 EntityUtils.toString 的一部分提供,例如根据您的场景使用 UTF-8 或 16。

IOUtils.toString() 来自 Apache Commons IO 也是更好的选择。