Android HttpURLConnection GET 客户端从服务器端获取json数据

首先,感谢很多版上大大的精华篇,让小菜鸟我可学习很多信息,完成这个程序

下面简单介绍一下 HttpURLConnection 如何从App访问服务器

1.如果你是在本机端建立服务器,下面用的IP地址只需要改后面存储文件的位置即可,如果不是本机端服务器,直接改成服务器实体IP地址即可。

2.HttpURLConnection这个对象需要在线程里才能执行,下面的程序代码,直接复制到你的Class底下即可使用,在new Thread这个子程序里,已经使用了线程,无须另外写程序处理。

3.线程最后一定要记的.start();才不会DeBug找很久还没找到问题,结果发现是忘了启动,犯傻了

 private void getJSON()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //默认IP地址
                String host = "http://10.0.2.2/SelectData.php";
                //建立HttpURLConnection对象
                HttpURLConnection conn = null;
                try
                {
                    //查看线程是否正常
                    if(Thread.interrupted()) throw new InterruptedException();
                    //设置链结
                    URL url = new URL(host);
                    //打开链结
                    conn = (HttpURLConnection) url.openConnection();
                    //设置读取链结时间,这里设置为10秒
                    conn.setReadTimeout(10000);
                    //设置联机链结时间,这里设置为15秒
                    conn.setConnectTimeout(15000);
                    //使用GET方式获取数据
                    conn.setRequestMethod("GET");
                    //URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true。 
                    conn.setDoInput(true);
                    //联机到服务器
                    conn.connect();
                    //查看线程是否正常
                    if(Thread.interrupted()) throw new InterruptedException();
                    //用缓冲区加载数据
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                    //逐行读出JSON
                    String jsonString = reader.readLine();
                    //打印JSON信息
                    Log.d("jsonStr",jsonString);
                    //关闭对象
                    reader.close();
                }
                catch (Exception e)
                {
                    //有错误,抛出例外
                    e.printStackTrace();
                }
                finally
                {
                    //如果有联机成功,最后关闭联机
                    if(conn != null) conn.disconnect();
                }
            }
        //最后启动线程
        }).start();
    }

猜你喜欢

转载自blog.csdn.net/Willseed/article/details/80076996