当前位置: 首页 > news >正文

Android 获取网页内容

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

WebUtill 类:


package com.example.ch_2013_4_11android_web;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class WebUtill {
	static HttpURLConnection myHttpUrlConnection;
	static InputStream myInputStream;

	/**
	 * 
	 * @param url
	 *            address
	 * @param method
	 *            post or get
	 * @param codeType
	 *            utf-8 or other
	 * @return
	 * @throws Exception
	 */
	public static byte[] getContent(URL url, String method, String codeType)
			throws Exception {
		URL myUrl = url;

		myHttpUrlConnection = (HttpURLConnection) myUrl.openConnection();
		// 设置连接超时
		myHttpUrlConnection.setConnectTimeout(6000);
		// get方式 发起请求
		myHttpUrlConnection.setRequestMethod(method);
		//
		if (myHttpUrlConnection.getResponseCode() != 200) {
			throw new RuntimeException("Fail to request url");
		}
		byte[] result;
		// 得到网络返回的流
		myInputStream = myHttpUrlConnection.getInputStream();
		//
		result = readDate(myInputStream, "utf-8");
		myInputStream.close();
		return result;
	}

	private static byte[] readDate(InputStream input, String mode)
			throws IOException {

		byte[] buff=new byte[input.available()];

		System.out.println("input 的长度:" + input.available());
		input.read(buff);
		return buff;
	}

	public static void closeConnection() {
		if (myHttpUrlConnection != null)
			myHttpUrlConnection.disconnect();
	}

}

MainActivity:

package com.example.ch_2013_4_11android_web;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

	

	// 以线程的方式发起一个请求
	//
	TextView myTextView = null, myTextView3 = null;
	//
	Button btn1, btn2, btn3;
	//
	ImageView myImageView;
	//
	URL myUrl;
	//
	HttpURLConnection myHttpURLConnection;
	//
	InputStream myInputStream;
	//
	String strResult = "";
	//
	ByteArrayOutputStream myByteArrayOutputStream;
	//
	
	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				Bundle b = msg.getData();
				String str = b.getString("value");
				myTextView3.setText(str);
			}
			if(msg.what==2){
				
			}
			if(msg.what==3){
				
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 实例化组件
		myTextView = (TextView) this.findViewById(R.id.txtInfo);
		//
		myImageView = (ImageView) this.findViewById(R.id.imageView1);
		//
		btn1 = (Button) this.findViewById(R.id.button1);
		//
		btn2 = (Button) this.findViewById(R.id.button2);
		//
		btn3 = (Button) this.findViewById(R.id.button3);
		//
		myTextView3 = (TextView) this.findViewById(R.id.mytext);
		//
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//
				new class1().start();
			}
		});
		//
		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//
				new class2().start();
			}
		});
		//
	
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@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;
	}

	class class1 extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				//
				myUrl = new URL("xxxxxxxxxxxxxx");
				//
				byte[] buff = WebUtill.getContent(myUrl, "GET", "utf-8");
				String strResult = new String(buff);
				Bundle data = new Bundle();
				data.putString("value", strResult);
				Message msg = new Message();
				msg.what = 1;
				msg.setData(data);
				handler.sendMessage(msg);
				// 直接输出内容
				System.out.println(strResult);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				//
				WebUtill.closeConnection();
			}
		}
	}

	// 通过网络获取一个图片
	class class2 extends Thread {

		@Override
		public void run() {
			//
			try {
				//
				myUrl = new URL("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif");
				//
				byte[] buff=WebUtill.getContent(myUrl, "GET", "utf-8");
				//
				final Bitmap bp = BitmapFactory.decodeByteArray(buff, 0, buff.length-1);
		        //
				handler.post(new Runnable() {
					@Override
					public void run() {
						myImageView.setImageBitmap(bp);
					}
				});
			} catch (Exception e) {
				//
				System.out.println(e.getMessage());
			}

		}

	}

	
}
xml:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/txtInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtInfo"
        android:text="从网页获取内容" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/imageView1"
        android:text="从网页获取图片并且替换" />

    <TextView
        android:id="@+id/mytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button2"
        android:text="TextView" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/mytext"
        android:text="传数据并且获取网页内容" />

</RelativeLayout>
需要在 AndroidManifest.xml中 添加 internet 权限 。



 

转载于:https://my.oschina.net/u/272065/blog/122054

相关文章:

  • 系统子模块_短信命令语法设计
  • 高效能人士的七个习惯(部分)
  • 以XML为中间文档格式的Excel电子表格向SVG图转换
  • Visifire for Windows 8 v2.1.1.0 发布
  • JNDI 学习(转)
  • 不可不知的移动色彩设计新趋势
  • Nosql入门知识(转)
  • linux 下oracle提示:the account is locked
  • CentOS中无法使用setup命令 -bash:setup: command not found
  • java InputStream读取数据问题
  • CITRIX 官方说明文档xenserver
  • 解决 KindEditor SWFUpload 批量上传检测用户登录状态的问题
  • mvc原理和mvc模式的优缺点
  • oracle教程之DML事务锁定的机制
  • iOS网络编程-iCloud键值数据存储编程实例
  • Bootstrap JS插件Alert源码分析
  • css布局,左右固定中间自适应实现
  • echarts花样作死的坑
  • Netty源码解析1-Buffer
  • node学习系列之简单文件上传
  • PHP面试之三:MySQL数据库
  • vue:响应原理
  • 订阅Forge Viewer所有的事件
  • 动态魔术使用DBMS_SQL
  • 浮现式设计
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 前端相关框架总和
  • 前端之React实战:创建跨平台的项目架构
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 手写双向链表LinkedList的几个常用功能
  • - 转 Ext2.0 form使用实例
  • CMake 入门1/5:基于阿里云 ECS搭建体验环境
  • 如何在招聘中考核.NET架构师
  • ​​​​​​​​​​​​​​Γ函数
  • ​TypeScript都不会用,也敢说会前端?
  • ​如何在iOS手机上查看应用日志
  • ​用户画像从0到100的构建思路
  • # MySQL server 层和存储引擎层是怎么交互数据的?
  • #include到底该写在哪
  • (4)STL算法之比较
  • (52)只出现一次的数字III
  • (C#)一个最简单的链表类
  • (动手学习深度学习)第13章 计算机视觉---微调
  • (亲测成功)在centos7.5上安装kvm,通过VNC远程连接并创建多台ubuntu虚拟机(ubuntu server版本)...
  • (三分钟了解debug)SLAM研究方向-Debug总结
  • (十三)Java springcloud B2B2C o2o多用户商城 springcloud架构 - SSO单点登录之OAuth2.0 根据token获取用户信息(4)...
  • (详细版)Vary: Scaling up the Vision Vocabulary for Large Vision-Language Models
  • (一)appium-desktop定位元素原理
  • (转)Linux下编译安装log4cxx
  • (转)编辑寄语:因为爱心,所以美丽
  • .Net Core/.Net6/.Net8 ,启动配置/Program.cs 配置
  • .Net Web项目创建比较不错的参考文章
  • /etc/fstab和/etc/mtab的区别
  • [<死锁专题>]
  • [20181219]script使用小技巧.txt