字节流解析json

时间:2022-05-26 04:02:21
package com.bwei.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;



public class NetWorkUtils {

    private static ByteArrayOutputStream baos;
   static String path="http://www.meirixue.com/api.php?c=index&a=index";
    public static String getjson(){

                try {
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    int responseCode = connection.getResponseCode();

                    baos = new ByteArrayOutputStream();

                    if(responseCode==200){
                        InputStream inputStream = connection.getInputStream();
                        int len;
                        byte[] arr = new byte[1024];
                        while ((len=inputStream.read(arr))!=-1){
                            baos.write(arr,0,len);
                        }

                    }
                    return baos.toString();
                } catch (Exception e) {

                    e.printStackTrace();
                }

        return "";
    }
}