Android开发——网络请求

目的:输入url,将返回的信息在textview里面显示
流程:

  1. 将输入的URL从String类型转换为URL对象
  2. 新建一个这条url的HTTPURLConnection(请求连接)
  3. 设置连接(方法,超时时间等)
  4. 请求联通连接
  5. 将获取到的返回数据放入输入流中
  6. 新建Reader对象将输入流中的数据解析成reader
  7. 新建一个buffer用于接收reader中的内容
  8. 用reader的read方法把reader的内容传入buffer中
  9. 将buffer转换成String
  10. 将转换后的string在onPreExecute方法里设置为textview的内容
    private String requestData(String urlString){

        URL url = null;
        try {
            url = new URL(urlString);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(30000);
            connection.setRequestMethod("GET");
            connection.connect();

            int responseCode = connection.getResponseCode();
            String responseMessage = connection.getResponseMessage();
            InputStream inputStream = connection.getInputStream();

            String content = null;
            if (responseCode == HttpURLConnection.HTTP_OK){
                //inputstream转换为字符串
                Reader reader = new InputStreamReader(inputStream, "UTF-8");
                char[] buffer = new char[1024];
                reader.read(buffer);
                content = new String(buffer);
            }

            return content;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

你可能感兴趣的:(Android)