1. 编写如下项目:

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组件的使用的更多相关文章

  1. android中利用HttpURLConnection进行Get、Post和Session读取页面。

    直接上代码,调用的时候要放在线程中. package slj.getsms; import java.io.BufferedReader; import java.io.InputStreamRead ...

  2. [Android基础]Android中使用HttpURLConnection

    HttpURLConnection继承了URLConnection,因此也能够向指定站点发送GET请求.POST请求.它在URLConnetion的基础上提供了例如以下便捷的方法. int getRe ...

  3. 客户机中PLSQL DEV访问虚拟机中的ORCLE11g,错误百出!

    客户机中PLSQL DEV访问虚拟机中的ORCLE11g,错误百出! 创建时间: 2017/10/14 18:44 作者: CNSIMO 标签: ORACLE 忙了一下午,只有两个字形容:麻烦!   ...

  4. 安卓中的消息循环机制Handler及Looper详解

    我们知道安卓中的UI线程不是线程安全的,我们不能在UI线程中进行耗时操作,通常我们的做法是开启一个子线程在子线程中处理耗时操作,但是安卓规定不允许在子线程中进行UI的更新操作,通常我们会通过Handl ...

  5. Android中判断网络连接是否可用及监控网络状态

    Android中判断网络连接是否可用及监控网络状态 作者: 字体:[增加 减小] 类型:转载 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限,接下来详细介绍Android ...

  6. Android中使用HttpURLConnection实现GET POST JSON数据与下载图片

    Android中使用HttpURLConnection实现GET POST JSON数据与下载图片 Android6.0中把Apache HTTP Client全部的包与类都标记为deprecated ...

  7. delphi 中OutputDebugString 函数的妙用(使用DebugView或者Pascal Analyzer软件,在运行过程中就能监视和捕捉日志,而且通过网络就能监视)

    原文地址 https://www.peganza.com/delphi-and-outputdebugstring.html 曾经想要实时监控您的Delphi应用程序,并能够查看日志消息吗?当然,您始 ...

  8. 【Azure 应用服务】Azure Function集成虚拟网络,设置被同在虚拟网络中的Storage Account触发,遇见Function无法触发的问题

    一切为了安全,所有的云上资源如支持内网资源访问,则都可以加入虚拟网络 问题描述 使用Azure Function处理Storage Account中Blob 新增,更新,删除等情况.Storage A ...

  9. Docker 外部访问容器Pp、数据管理volume、网络network 介绍

    Docker 外部访问容器Pp.数据管理volume.网络network 介绍 外部访问容器 容器中可以运行一些网络应用,要让外部也可以访问这些应用,可以通过 -P 或 -p 参数来 指定端口映射. ...

随机推荐

  1. Docker控制组

    控制组是 Linux 容器机制的另外一个关键组件,负责实现资源的审计和限制. 它提供了很多有用的特性:以及确保各个容器可以公平地分享主机的内存.CPU.磁盘 IO 等资源:当然,更重要的是,控制组确保 ...

  2. Linux下的有用命令

    在之前的博客<Linux下常用命令与使用技巧>中,介绍了Linux的常用命令,在今天的博客中,给大家介绍其他的有用命令. 1.文本转换命令 在Linux下工作,我们不可避免地要和文件格式做 ...

  3. 百度地图JS 搜索悬浮窗功能

    这个需求的效果类似下面的截图,主要还是利用百度地图中自定义控件的功能,挺简单的.文档地址在这 http://lbsyun.baidu.com/index.php?title=jspopular 效果图 ...

  4. webpack 将不同类型的文件输出到不同文件夹

    参考:https://stackoverflow.com/questions/33058964/configure-webpack-to-output-images-fonts-in-a-separa ...

  5. ToolBar控件详解

    ToolBar控件详解 在Activity中添加ToolBar 1.添加库 dependencies { ... compile "com.android.support:appcompat ...

  6. ubuntu垃圾清理命令

    ubuntu的空间莫名不够用了 通过系统自带的工具磁盘使用分析器,发现var文件下面的log100多个g,这个日志文件是可以删除的,然后tmp文件也是可以删除的. 1.sudo rm -rf /tmp ...

  7. static修饰符详解

    static表示"全局"或者"静态"的意思,用来修饰成员变量和成员方法,也可以形成静态static代码块,但是Java语言中没有全局变量的概念. 被static ...

  8. 第三方开源动画库EasyAnimation中一个小bug的修复

    看过iOS动画之旅的都知道,其中在最后提到一个作者写的开源动画库EasyAnimation(以下简称EA). EA对CoreAnimation中的view和layer动画做了更高层次的包装和抽象,使得 ...

  9. Swift延迟加载的一种用途

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 有以下一种情况: 我们试图用Cocoa的语音合成类NSSpee ...

  10. 3.QT事件处理,消息过滤器

     1  新建一个项目:06Event 新建cpp文件 06Event.pro HEADERS += \ MyWidget.h SOURCES += \ MyWidget.cpp QT += wid ...