Android 读取网络数据
发布日期:2021-06-30 22:35:00
浏览次数:3
分类:技术文章
本文共 2901 字,大约阅读时间需要 9 分钟。
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; }}
转载地址:https://lovoo.blog.csdn.net/article/details/51223558 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2024年04月28日 17时46分46秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
c++实现彩色炫酷(?)画面
2019-04-30
c++马拦过河卒
2019-04-30
2019NOIP D4题 加工领奖
2019-04-30
1997年世界黑客大赛获奖作品
2019-04-30
论DEV-C++怎样才能做窗口
2019-04-30
Failed to connect to github.com port 443: Operation timed out和弹出无法打开"GoogleSoftwareUpdate.bundle"
2019-04-30
2021.5.19 JS高级第二天
2019-04-30
2021.5.20 JS高级第三天
2019-04-30
2021.5.21 Jquery
2019-04-30
2021.5.22 Jquery
2019-04-30
2021.5.25 JSON
2019-04-30
2021.5.25 Flex
2019-04-30
2021.5.28 AJAX
2019-04-30
正则表达式
2019-04-30
过滤器Filter
2019-04-30
2021.6.1 Array补充
2019-04-30
【收藏】Markdown笔记
2019-04-30
离散数学-图论
2019-04-30
啊沙发沙发
2019-04-30
2021-07-02
2019-04-30