Parse JSON from HttpURLConnection object

后端 未结 5 1858
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 11:04

I am doing basic http auth with the HttpURLConnection object in Java.

        URL urlUse = new URL(url);
        HttpURLConnection conn = null;
         


        
5条回答
  •  情歌与酒
    2020-11-27 12:01

    You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider 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;
    }
    

    And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

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

    There is a sample of AuthMsg class:

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

    JSON returned by http://localhost/authmanager.php must look like this:

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

    Regards

提交回复
热议问题