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
- Android 读取网络数据
- Android 读取网络数据
- android HttpURLConnection 连接网络 读取返回数据
- 读取网络数据
- 从网络读取数据
- 读取网络数据
- ELKStack读取网络数据
- 网络数据读取框架
- android 读取网络在传输数据时的状态
- android使用Http的Get方式读取网络数据
- Android程序:使用Http的Get方式读取网络数据
- android 使用Http的Get方式读取网络数据
- android 使用Http的POST方式读取网络数据
- Android---数据读取、存储、删除(内存储/SD卡存储/网络数据读取存储)
- android读取网络图片
- android读取网络图片
- Android读取网络图片
- Android网络流读取
- php 获取客户端的ip、地理信息、浏览器信息、本地真实ip
- java线程模型 线程池
- SystemUI statusbar 更换自己的UI图标
- C
- 网易互娱2017实习生招聘游戏研发工程师在线笔试第二场(神奇的数)
- Android 读取网络数据
- [参考]redis存储商品信息,自增订单或商品id,缓存评论!
- java毕向东听课笔记23(集合框架-List集合具体对象)
- LeetCode208 Implement Trie (Prefix Tree) Java
- JSP基础
- poj2524 Ubiquitous Religions
- 【证明可用】Ubuntu14.04/16.04命令行快速安装Ruby和Rails运行环境
- Wiki
- 【BFS】初探