Android开发-网络请求数据

如何用网络请求数据呢?

第一步 创建一个工具类NetWorks 在工具类中写一个方法(getJson)
这个类里可以写很多方法 不仅仅限于网络请求数据 比如常见的还有判断网络的连接状态等等…在其他的页面可以调用到这个工具类里的方法

public class NetWorks {

    //网络请求数据 的方法
    public static String getJson(String urlString){
        try {
            URL url = new URL( urlString );
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
                //按行读取
                String temp="";
                String json="";
                while ((temp=reader.readLine())!=null){
                    json+=temp;
                }
                return json;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }//网络请求数据

}

猜你喜欢

转载自blog.csdn.net/qq_25560357/article/details/84972977