Android 读取网络数据

来源:互联网 发布:arch linux安装教程 编辑:程序博客网 时间:2024/05/20 14:43
public class HtmlActivity extends Activity implements OnClickListener {    private static final int SUCCESS = 0;    private static final int FAILURE = 1;    private static final int ERROR = 2;    private Button btnView;    private TextView tvContent;    private EditText etUrl;    private Handler mHandler = new Handler() {        public void handleMessage(Message msg) {            switch (msg.what) {            case SUCCESS:                String content = (String) msg.obj;                tvContent.setText(content);                break;            case FAILURE:                break;            case ERROR:                break;            default:                break;            }        };    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_html);        initView();    }    private void initView() {        btnView = (Button) findViewById(R.id.btn_html);        tvContent = (TextView) findViewById(R.id.tv_content);        etUrl = (EditText) findViewById(R.id.et_url);        btnView.setOnClickListener(this);    }    @Override    public void onClick(View v) {        if (v == btnView) {            try {                URL url = new URL(etUrl.getText().toString());                HttpURLConnection conn = (HttpURLConnection) url.openConnection();                conn.setRequestMethod("get");                conn.setConnectTimeout(5000);                conn.setDoInput(true);                conn.setDoOutput(true);                conn.setUseCaches(false);                // conn.setRequestProperty("", newValue);                conn.connect();                if (conn.getResponseCode() == 200) {                    String result = NetUtils.parseStream(conn.getInputStream());                    Message msg = Message.obtain();                    msg.what = SUCCESS;                    msg.obj = result;                    mHandler.sendMessage(msg);                } else {                    mHandler.sendEmptyMessage(FAILURE);                }            } catch (Exception e) {                e.printStackTrace();                mHandler.sendEmptyMessage(ERROR);            }        }    }}
public class NetUtils {    public static String parseStream(InputStream inputStream) {        ByteArrayOutputStream bos = new ByteArrayOutputStream();        try {            byte[] buffer = new byte[1024];            int len = -1;            while((len = inputStream.read(buffer))!=-1){                bos.write(buffer, 0, len);            }            inputStream.close();            bos.close();        } catch (IOException e) {            e.printStackTrace();            return "获取失败";        }        try {            return new String(bos.toByteArray(),"utf-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return null;    }}
0 0
原创粉丝点击