Android: HttpURLConnection获取JSON数据

public class GetJsonDataTask extends AsyncTask<String, Void, String> {
    private TextView tv;

    public GetJsonDataTask(TextView tv) {
        super();
        this.tv = tv;
    }
    /**
     * 这里的String参数对应AsyncTask中的第一个参数   
     * 这里的String返回值对应AsyncTask的第三个参数  
     * 该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改  
     * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作  
     */
    @Override
    protected String doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            String resp_content = "";
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                resp_content = readInputStreamToString(is);
            }
            return resp_content;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)
     * 在doInBackground方法执行结束之后在运行,并且运行在UI线程当中 可以对UI控件进行设置
     */
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        tv.setText(s);
    }

    //字节流转换成字符串
    private static String readInputStreamToString(InputStream is) {
        byte[] result;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            baos.close();
            result = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return "获取数据失败";
        }
        return new String(result);
    }
}

  

posted on 2017-08-01 17:02  MojoJojo  阅读(1111)  评论(0)    收藏  举报

导航