10_Android中通过HttpUrlConnection访问网络,Handler和多线程使用,读取网络html代码并显示在界面上,ScrollView组件的使用
编写如下项目:
2 编写Android清单文件
|
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.itheima28.htmldemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.itheima28.htmldemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
3 编写布局文件activity_main.xml
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:id="@+id/et_url" android:layout_width="0dip" android:text="http://www.baidu.com" android:layout_height="wrap_content" android:singleLine="true" android:layout_weight="1"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="getHtml" android:text="GO"/> </LinearLayout> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/tv_html" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </ScrollView> </LinearLayout> |
4 编写Activity的类MainActivity如下:
|
package com.itheima28.htmldemo; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private static final int SUCCESS = 0; protected static final int ERROR = 1; private EditText etUrl; private TextView tvHtml; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case SUCCESS: tvHtml.setText((String) msg.obj); break; case ERROR: Toast.makeText(MainActivity.this, "访问失败", 0).show(); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etUrl = (EditText) findViewById(R.id.et_url); tvHtml = (TextView) findViewById(R.id.tv_html); } public void getHtml(View v) { final String url = etUrl.getText().toString(); new Thread(new Runnable() { @Override public void run() { // 请求网络 String html = getHtmlFromInternet(url); if(!TextUtils.isEmpty(html)) { // 更新textview的显示了 Message msg = new Message(); msg.what = SUCCESS; msg.obj = html; handler.sendMessage(msg); } else { Message msg = new Message(); msg.what = ERROR; handler.sendMessage(msg); } } }).start(); } /** * 根据给定的url访问网络, 抓去html代码 * @param url * @return */ protected String getHtmlFromInternet(String url) { try { URL mURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); conn.setReadTimeout(5000); // conn.connect(); int responseCode = conn.getResponseCode(); if(responseCode == 200) { InputStream is = conn.getInputStream(); String html = getStringFromInputStream(is); return html; } else { Log.i(TAG, "访问失败: " + responseCode); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 根据流返回一个字符串信息 * @param is * @return * @throws IOException */ private String getStringFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } is.close(); String html = baos.toString(); // 把流中的数据转换成字符串, 采用的编码是: utf-8 String charset = "utf-8"; if(html.contains("gbk") || html.contains("gb2312") || html.contains("GBK") || html.contains("GB2312")) { // 如果包含gbk, gb2312编码, 就采用gbk编码进行对字符串编码 charset = "gbk"; } html = new String(baos.toByteArray(), charset); // 对原有的字节数组进行使用处理后的编码名称进行编码 baos.close(); return html; } } |
10_Android中通过HttpUrlConnection访问网络,Handler和多线程使用,读取网络html代码并显示在界面上,ScrollView组件的使用的更多相关文章
- android中利用HttpURLConnection进行Get、Post和Session读取页面。
直接上代码,调用的时候要放在线程中. package slj.getsms; import java.io.BufferedReader; import java.io.InputStreamRead ...
- [Android基础]Android中使用HttpURLConnection
HttpURLConnection继承了URLConnection,因此也能够向指定站点发送GET请求.POST请求.它在URLConnetion的基础上提供了例如以下便捷的方法. int getRe ...
- 客户机中PLSQL DEV访问虚拟机中的ORCLE11g,错误百出!
客户机中PLSQL DEV访问虚拟机中的ORCLE11g,错误百出! 创建时间: 2017/10/14 18:44 作者: CNSIMO 标签: ORACLE 忙了一下午,只有两个字形容:麻烦! ...
- 安卓中的消息循环机制Handler及Looper详解
我们知道安卓中的UI线程不是线程安全的,我们不能在UI线程中进行耗时操作,通常我们的做法是开启一个子线程在子线程中处理耗时操作,但是安卓规定不允许在子线程中进行UI的更新操作,通常我们会通过Handl ...
- Android中判断网络连接是否可用及监控网络状态
Android中判断网络连接是否可用及监控网络状态 作者: 字体:[增加 减小] 类型:转载 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限,接下来详细介绍Android ...
- Android中使用HttpURLConnection实现GET POST JSON数据与下载图片
Android中使用HttpURLConnection实现GET POST JSON数据与下载图片 Android6.0中把Apache HTTP Client全部的包与类都标记为deprecated ...
- delphi 中OutputDebugString 函数的妙用(使用DebugView或者Pascal Analyzer软件,在运行过程中就能监视和捕捉日志,而且通过网络就能监视)
原文地址 https://www.peganza.com/delphi-and-outputdebugstring.html 曾经想要实时监控您的Delphi应用程序,并能够查看日志消息吗?当然,您始 ...
- 【Azure 应用服务】Azure Function集成虚拟网络,设置被同在虚拟网络中的Storage Account触发,遇见Function无法触发的问题
一切为了安全,所有的云上资源如支持内网资源访问,则都可以加入虚拟网络 问题描述 使用Azure Function处理Storage Account中Blob 新增,更新,删除等情况.Storage A ...
- Docker 外部访问容器Pp、数据管理volume、网络network 介绍
Docker 外部访问容器Pp.数据管理volume.网络network 介绍 外部访问容器 容器中可以运行一些网络应用,要让外部也可以访问这些应用,可以通过 -P 或 -p 参数来 指定端口映射. ...
随机推荐
- 安卓热修复之AndFIX
我致力于最新的前沿安卓技术分析和使用教学,不打算将很多很深的东西,因为有多少人愿意沉下你的心境去学习难点?我一般只会简单提及.文字错漏在所难免还希望同学们喜欢 热修复介绍 热修复是什么? 如果你一个项 ...
- 这是最好的时光 这是最坏的时光 v0.1.1.1
这是最好的时光 这是最坏的时光 v0.1.1.1 1.2 学校的生活二三事之大学 话说上一回,扯了一下我青涩的少年往事,大家反响不一,有叫好的,有吐槽的,有字字码过的,也有一目十行的.我的心情也是随着 ...
- Hive基本原理及环境搭建
今天我主要是在折腾这个Hive,早上看了一下书,最开始有点凌乱,后面慢慢地发现,hive其实挺简单的,以我的理解就是和数据库有关的东西,那这样的话对我来说就容易多啦,因为我对sql语法应该是比较熟悉了 ...
- C++ 中const作用
一.对const与#define的特点及区别的理解 #define只是用来做文本替换的,#define常量的生命周期止于编译期,它存在于程序的代码段,在实际程序中它只是一个常数,一个命令中的参数,并没 ...
- Android自定义ViewGroup(四、打造自己的布局容器)
转载请标明出处: http://blog.csdn.net/xmxkf/article/details/51500304 本文出自:[openXu的博客] 目录: 简单实现水平排列效果 自定义Layo ...
- Swift基础之守卫语句guard
本篇文章翻译自:http://ericcerney.com/swift-guard-statement/原作者:ecerney该语法为swift2.0之后添加的新特性 最开始在Apple的Platfo ...
- Struts 2 之校验器
对于输入校验,Struts2提供了两种方式,1.使用validate方法:2.基于XML配置实现 . validate()方法 支持校验的Action必须实现Validateable接口,一般直接继承 ...
- ubuntu mysql表名大小写区分
近期开发线上操作系统用的ubuntu,数据库用的mysql,突然发现mysql表名大写报错,找一下原因,看了下mysql的配置,果真可以设置,窃喜. 先找到你MySQL的my.cnf配置文件并修改,当 ...
- iOS中使用iCloud一些需要注意的地方(Xcode7.2)
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 在自己的App中如何使用iCloud有很多文章可以查阅,这里把 ...
- [ExtJS5学习笔记]第十四节 Extjs5中data数据源store和datapanel学习
本文地址:http://blog.csdn.net/sushengmiyan/article/details/39031383 sencha官方API:http://docs.sencha.com/e ...