java - 从 HttpURLConnection 对象解析 JSON

标签 java html json parsing httpurlconnection

我正在使用 Java 中的 HttpURLConnection 对象进行基本的 http 身份验证。

        URL urlUse = new URL(url);
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) urlUse.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-length", "0");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        conn.connect();

        if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
        {
            success = true;
        }

我期待一个 JSON 对象,或有效 JSON 对象格式的字符串数据,或带有有效 JSON 的简单纯文本的 HTML。 HttpURLConnection 返回响应后如何访问它?

最佳答案

您可以使用以下方法获取原始数据。顺便说一句,此模式适用于 Java 6。如果您使用的是 Java 7 或更新版本,请考虑 try-with-resources pattern .

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

然后您可以将返回的字符串与 Google Gson 一起使用将 JSON 映射到指定类的对象,如下所示:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

有一个 AuthMsg 类的示例:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

http://localhost/authmanager.php 返回的 JSON必须是这样的:

{"code":1,"message":"Logged in"}

问候

关于java - 从 HttpURLConnection 对象解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10500775/

相关文章:

java - 使用 Java Mac 获取 PID

asp.net - 如何通过 JQuery/Javascript 调用保护我的 Web 服务?

java - 如何仅针对给定的单个端点忽略 JsonProperty 并让它适用于其他端点

JavaScript 作用域冲突

javascript - 如何使用JS调用iframe中的函数?

html - Internet Explorer 特定的 html 无序列表错误

json - 想通过Node.js存储到Redis

java - 如何将工作区资源 IFolder 写入磁盘(Eclipse RCP)?

Java 在构造函数中实现 ActionListener 方法

java - 如何在hadoop 0.23.0 MR2上运行和编译java程序