Android中实现地址栏输入网址能浏览该地址网页源码并操作访问网络
发布时间:2022-08-21 16:11:42
标签:地址栏,网址,网页源码
首先实现简单布局:
<EditText
android:id="@+id/et_url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:text="@string/url_text" >
<requestFocus android:layout_width="match_parent" />
</EditText>
<Button
android:id="@+id/btn_ie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/et_url"
android:onClick="sendHttp"
android:text="@string/btn_text" />
<ScrollView
android:id="@+id/sv_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn_ie" >
<TextView
android:id="@+id/tv_ie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/ie_text" />
</ScrollView>
在Stirng中
<string name="url_text">http://luochuang.iteye.com/blog/1606231</string>
<string name="btn_text">浏览</string>
<string name="ie_text">显示浏览网页内容</string>
新建类文件 :
首先MainActivity 中代码 :
public class MainActivity extends Activity {
// 声明控件
public EditText et_url;
public TextView tv_ie;
// 网路操作类
public NetWorkUtils netWorkUtils;
private Handler handler;
public String content;
public static final int TEXT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取et_url对象
et_url = (EditText) findViewById(R.id.et_url);
tv_ie = (TextView) findViewById(R.id.tv_ie);
// 实例化
netWorkUtils = new NetWorkUtils(this);
// 实例化这个处理者
handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TEXT:
tv_ie.setText(content);// 设置显示的文本
break;
default:
break;
}
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sendHttp(View v) {
// 设置网络
boolean flag = netWorkUtils.setActiveNetWork();
if (flag) {
// run方法 执行完毕 这个线程就消耗了
// 子线程
new Thread(new Runnable() {
@Override
public void run() {
send();
handler.sendEmptyMessage(TEXT);
}
}).start();
}
}
// 发送请求操作
@SuppressLint("NewApi")
public void send() {
// 获取url的path路径
String path = et_url.getText().toString();
if (path.isEmpty()) {
Toast.makeText(MainActivity.this, "访问 的url地址不能为空",
Toast.LENGTH_LONG).show();
} else {
content = HttpUtils.sendGet(path);
}
/*// 设置网络
netWorkUtils.setActiveNetWork();
// 获取url的path路径
String path = et_url.getText().toString();
if (path.isEmpty()) {
Toast.makeText(MainActivity.this, "访问 的url地址不能为空",
Toast.LENGTH_LONG).show();
} else {
try {
// 设置访问的url
URL url = new URL(path);
// 打开请求
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 设置请求的信息
httpURLConnection.setRequestMethod("GET");
// 判断服务器是否响应成功
if (httpURLConnection.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = httpURLConnection.getInputStream();
// 字节输出流
ByteArrayOutputStream bops = new ByteArrayOutputStream();
// 读取数据的缓存区
byte buffer[] = new byte[1024];
// 读取长度记录
int len = 0;
// 循环读取
while ((len = is.read(buffer)) != -1) {
bops.write(buffer, 0, len);
}
// 把读取的内容转换成byte数组
byte data[] = bops.toByteArray();
// 把转换成字符串
content = new String(data);
} else {
Toast.makeText(MainActivity.this, "服务器响应错误",
Toast.LENGTH_LONG).show();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
}
public class HttpUtils {
public static String sendGet(String path) {
String content = null;
try {
// 设置访问url
URL url = new URL(path);
// 打开请求
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 设置请求的信息
httpURLConnection.setRequestMethod("GET");
// 设置请求是否超时时间
httpURLConnection.setConnectTimeout(5000);
// 判断服务器是否响应成功
if (httpURLConnection.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = httpURLConnection.getInputStream();
byte data[] = StreamTools.isToData(is);
// 把转换成字符串
content = new String(data);
// 内容编码方式
if (content.contains("gb2312")) {
content = new String(data, "gb2312");
}
}
// 断开连接
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
public class StreamTools {
public static byte[] isToData(InputStream is) throws IOException{
//字节输出流
ByteArrayOutputStream bops = new ByteArrayOutputStream();
//读取数据的缓存区
byte buffer[] = new byte[1024];
//读取长度 的记录
int len = 0;
//循环读取
while((len = is.read(buffer)) != -1){
bops.write(buffer, 0, len);
}
//把读取的内容转换成 byte数组
byte data[] = bops.toByteArray();
return data;
}
}
public class NetWorkUtils {
private Context context;
// 网路链接管理对象
public ConnectivityManager connectivityManager;
public NetWorkUtils(Context context) {
this.context = context;
// 获取网络链接的对象
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
//public void setActiveNetWork() {
public boolean setActiveNetWork() {
boolean flag = false;
// 获取可用的网络链接对象
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
new AlertDialog.Builder(context)
.setTitle("网络不可用")
.setMessage("可以设置网络?")
.setPositiveButton("确认",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(context, "点击确认",
Toast.LENGTH_LONG).show();
// 声明意图
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory("android.intent.category.LAUNCHER");
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings"));
intent.setFlags(0x10200000);
// 执行意图
context.startActivity(intent);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
// 必须.show();
}).show();
}
//判断网络是否可用
if(networkInfo!=null){
flag=true;
}
return flag;
}
}
然后就是要在AndroidManifest.xml中添加 可以访问网络的权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>


猜你喜欢
- 引言前边两章说了点基础的,从这章开始,我们挖挖源码。看看RocketMQ是怎么工作的。首先呢,这个生产者就是送孩子去码头的家长,孩子们呢,就
- 装饰器模式概述装饰器模式(Decorator Pattern)也称为包装模式(Wrapper Pattern),属于结构型模式。它是指在不改
- 一、题目描述题目实现:运行客户端,连接服务器。二、解题思路首先需要启动上题的ServerSocketFrame服务,这样客户端运行时,才能连
- 服务器端代码:import java.io.BufferedReader; import java.io.InputStreamR
- 前言提起子类、基类和方法继承这些概念,肯定大家都非常熟悉。毕竟,作为一门支持OOP的语言,掌握子类、基类是学习C#的基础。不过,这些概念虽然
- 本文实例讲述了C#基于基姆拉尔森算法计算指定日期是星期几的方法。分享给大家供大家参考。具体分析如下:基姆拉尔森计算公式 W= (d+2*m+
- 现在的模拟器的功能太强大,从蓝牙,传感器等配件到IMEI,Mac,以及手机硬件信息什么都可以模拟为了防止用户利用模拟器模仿真机进行刷单,刷流
- 目录1、先创建对应相关操作的注解1.1 bTable 标识表1.2 DbPrimaryKey 标识主键1.3 DbFil
- 一、Java把这些不同来源和目标的数据都统一抽象为数据流。Java语言的输入输出功能是十分强大而灵活的。在Java类库中,IO部分的内容是很
- 当前使用的IDEA版本是2020.1。随着IDEA版本的升级,有些插件不再支持,而有些插件变成了收费插件,这些插件将不再推荐。以下列举的,都
- 加密解密本身并不是难事,问题是在何时去处理?定义一个过滤器,将请求和响应分别拦截下来进行处理也是一个办法,这种方式虽然粗暴,但是灵活,因为可
- 1、DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1
- a.在.xaml文件中拖入一个datagrid,然后添加列名,使用Binding="{Binding 数据库中的列名称}"
- 先利用jsoup将得到的html代码“标准化”(Jsoup.parse(String html))方法,然后利用FileWiter将此htm
- spring-AOP 及 AOP获取request各项参数AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事
- 1. 你知道volatile是如何保证可见性吗?我们先看一组代码:public class VolatileVisibleDemo { &n
- 本文实例讲述了C#简单创建和删除目录的方法。分享给大家供大家参考。具体如下:using System;using System.IO;cla
- 您好,我是贾斯汀,欢迎又进来学习啦!【学习背景】学习Java的小伙伴,都知道想要提升个人技术水平,阅读JDK源码少不了,但是说实话还是有些难
- 偶然机会看到一种对象初始的方式:// 新建一个列表,并赋值 "Harry","Tony","
- 1、什么是FeignFeign 是 Spring Cloud Netflix 组件中的一个轻量级 RESTful 的 HTTP 服务客户端,