从HttpURLConnection对象解析JSON

从HttpURLConnection对象解析JSON,第1张

从HttpURLConnection对象解析JSON

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

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 pre;    private String message;    public int getCode() {        return pre;    }    public void setCode(int pre) {        this.pre = pre;    }    public String getMessage() {        return message;    }    public void setMessage(String message) {        this.message = message;    }}

由返回的JSON必须如下所示:

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5566753.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存