首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从HttpURLConnection对象解析JSON

从HttpURLConnection对象解析JSON
EN

Stack Overflow用户
提问于 2012-05-08 22:37:56
回答 5查看 169.9K关注 0票数 65

我正在用Java中的HttpURLConnection对象做基本的http auth。

        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访问它?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-05-08 23:24:37

您可以使用以下方法获取原始数据。顺便说一句,此模式适用于Java6。如果您使用的是Java7或更高版本,请考虑使用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映射到指定类的object,如下所示:

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"}

问候

票数 117
EN

Stack Overflow用户

发布于 2012-05-08 22:48:05

定义以下函数(不是我的,不确定我很久以前在哪里找到的):

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
return sb.toString();

}

然后:

String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
    {
        success = true;
        InputStream response = conn.getInputStream();
        jsonReply = convertStreamToString(response);

        // Do JSON handling here....
    }
票数 11
EN

Stack Overflow用户

发布于 2014-06-16 19:58:22

此外,如果您希望在http错误(400-5**代码)的情况下解析您的对象,您可以使用以下代码:(只需将'getInputStream‘替换为'getErrorStream':

    BufferedReader rd = new BufferedReader(
            new InputStreamReader(conn.getErrorStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();
    return sb.toString();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10500775

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档