Android 读取网络数据
16lz
2021-01-23
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; }}
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer