Parse JSON from HttpURLConnection object

后端 未结 5 1839
被撕碎了的回忆
被撕碎了的回忆 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 11:40

    In addition, if you wish to parse your object in case of http error (400-5** codes), You can use the following code: (just replace 'getInputStream' with '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();
    
    0 讨论(0)
  • 2020-11-27 11:51

    This function will be used get the data from url in form of HttpResponse object.

    public HttpResponse getRespose(String url, String your_auth_code){
    HttpClient client = new DefaultHttpClient();
    HttpPost postForGetMethod = new HttpPost(url);
    postForGetMethod.addHeader("Content-type", "Application/JSON");
    postForGetMethod.addHeader("Authorization", your_auth_code);
    return client.execute(postForGetMethod);
    }
    

    Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.

    String jsonString     =     
    EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/    blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new    CustomJsonDeserialiser());
    final Gson gson = gsonBuilder.create();
    JsonElement json = new JsonParser().parse(jsonString);
    JsonJavaModel pojoModel = gson.fromJson(
                        jsonElementForJavaObject, JsonJavaModel.class);
    

    This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:

    public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel>         {
    
    @Override
    public JsonJavaModel deserialize(JsonElement json, Type type,
                                     JsonDeserializationContext arg2) throws    JsonParseException {
        final JsonJavaModel jsonJavaModel= new JsonJavaModel();
        JsonObject object = json.getAsJsonObject();
    
        try {
         jsonJavaModel.content = object.get("Content").getAsString()
         jsonJavaModel.title = object.get("Title").getAsString()
    
        } catch (Exception e) {
    
            e.printStackTrace();
        }
        return jsonJavaModel;
    }
    

    Include Gson library and org.apache.http.util.EntityUtils;

    0 讨论(0)
  • 2020-11-27 11:55

    Define the following function (not mine, not sure where I found it long ago):

    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();
    

    }

    Then:

    String jsonReply;
    if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
        {
            success = true;
            InputStream response = conn.getInputStream();
            jsonReply = convertStreamToString(response);
    
            // Do JSON handling here....
        }
    
    0 讨论(0)
  • 2020-11-27 12:00

    The JSON string will just be the body of the response you get back from the URL you have called. So add this code

    ...
    BufferedReader in = new BufferedReader(new InputStreamReader(
                                conn.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) 
        System.out.println(inputLine);
    in.close();
    

    That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.

    Here's an example using JSON-LIB

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题