HttpsURLConnection转换为JSONObject

时间:2016-07-14 11:40:03

标签: java json

try {         

   url = new URL(https_url);
   HttpsURLConnection posts = (HttpsURLConnection)url.openConnection();

} catch (MalformedURLException e) {
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
}  

如何将HttpsURLConnection 帖子对象转换为JSONObject?提前致谢。 :)

  

答案:using the mvn org.json

3 个答案:

答案 0 :(得分:1)

  1. 寻找一个JSON库(那里有很多,从GSON,Jackson等奇特的东西到更轻量级的东西)。
  2. 阅读其文档。
  3. 直接传递InputStream,将其包装在阅读器中或将其作为String读取,具体取决于API。

答案 1 :(得分:0)

您可以尝试GSon使用Json,但我怀疑您确实需要放入jSon posts对象。另一种情况是你想把HttpsURLConnection响应放到json上。顺便说一句,您可以使用纯字符串创建jSon对象,如: "

String json = "{"+"hello"+":"+"hello I am json Object"+"}";

答案 2 :(得分:0)

我认为这里有一个错误。您正在创建的对象是连接对象。没有要提取的JSON。如果您想从URL获取JSON,请参阅下面的示例代码。

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}