Android 读取网络数据
发布日期:2021-06-30 22:35:00 浏览次数:2 分类:技术文章

本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android 使用HttpGet进行登录
下一篇:Android 使用事物处理

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月15日 09时09分22秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章