Android(安卓)读取网络数据
16lz
2021-12-04
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; }}
更多相关文章
- 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
- Android(安卓)handler异步更新
- android获取指定路径下目录文件
- ANDROID截屏
- Android(安卓)基于GeolocationAPI的基站定位
- Android(安卓)通过短链接,获取长连接
- android获取mac地址
- 获取Android唯一设备号
- Android(安卓)之获取图片及视频缩略图