Parse JSON from HttpURLConnection object

后端 未结 5 1852
被撕碎了的回忆
被撕碎了的回忆 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: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....
        }
    

提交回复
热议问题