从网络获取图片与网页

1>网络----获取数据(图片、网页、xml、Json等)
A.从网络获取一张图片,然后显示在手机上;
B.从网络获取网页的html代码,然后显示在手机上;

从Internet获取数据

利用HttpURLConnection对象,我们可以从网络中获取网页数据.
URL url = new URL("http://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);//设置连接超时
conn.setRequestMethod(“GET”);//以get方式发起请求
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//得到网络返回的输入流
String result = readData(is, "GBK");
conn.disconnect();
//第一个参数为输入流,第二个参数为字符集编码
public static String readData(InputStream inSream, String charsetName) throws Exception{
	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
	byte[] buffer = new byte[1024];
	int len = -1;
	while( (len = inSream.read(buffer)) != -1 ){
		outStream.write(buffer, 0, len);
	}
	byte[] data = outStream.toByteArray();
	outStream.close();
	inSream.close();
	return new String(data, charsetName);
}


利用HttpURLConnection对象,我们可以从网络中获取文件数据.
URL url = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();
readAsFile(is, "Img269812337.jpg"); 

public static void readAsFile(InputStream inSream, File file) throws Exception{
	FileOutputStream outStream = new FileOutputStream(file);
	byte[] buffer = new byte[1024];
	int len = -1;
	while( (len = inSream.read(buffer)) != -1 ){
		outStream.write(buffer, 0, len);
	}
 	outStream.close();
	inSream.close();
}
j2se测试网络代码;

ImageRequest.java

package cn.itcast.net;

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


public class ImageRequest {
	public static void main(String[] args) throws Exception {
		//URL封装web访问路径;
		URL url = new URL("http://1801.img.pp.sohu.com.cn/images/2010/1/4/20/5/126a35eabd5mm.jpg");
		//打开连接;
		HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5*1000);
		
		InputStream inStream = conn.getInputStream();//通过输入流获取图片数据;
		byte[] imageData = readInputStream(inStream);
		File imagefile = new File("beauty.jpg"); 
		FileOutputStream fos = new FileOutputStream(imagefile);
		fos.write(imageData);  //把图片的二进制数据写入到文件中;
		fos.close();
	}
	
	/**
	 * 从流里读取数据;以二进制形式返回;
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		
		int len = 0;
		while((len = inStream.read(buffer)) != -1){//没有读到末尾一直循环;
			outStream.write(buffer, 0, len);//将buffer的数据写到内存中;
		}
		
		inStream.close();
		return outStream.toByteArray();
	}
}
android 浏览网页图片:

StreamTool.java--------工具类

package cn.itcast.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {
	
	/**
	 * 从流里读取数据;以二进制形式返回;
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		
		int len = 0;
		while((len = inStream.read(buffer)) != -1){//没有读到末尾一直循环;
			outStream.write(buffer, 0, len);//将buffer的数据写到内存中;
		}
		
		inStream.close();
		return outStream.toByteArray();
	}
}

ImageService.java------服务类

package cn.itcast.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.itcast.utils.StreamTool;

public class ImageService {
	
	/**
	 * 返回图像的二进制数据;
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static byte[] getImage(String path) throws Exception {
		//URL封装web访问路径;
		URL url = new URL(path);
		//打开连接;
		HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5*1000);
		
		InputStream inStream = conn.getInputStream();//通过输入流获取图片数据;
		return StreamTool.readInputStream(inStream);
		
	}
}


资源文件
strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">图片浏览器</string>
    <string name="urlpath">网络图片地址</string>
    <string name="button">显示</string>
    <string name="error">网络连接超时</string>

</resources>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="@string/urlpath"
	    />
	    
	<EditText  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="http://1801.img.pp.sohu.com.cn/images/2010/1/4/20/5/126a35eabd5mm.jpg"
	    android:id="@+id/urlpath"
	    />
	    
	<Button
	 	android:layout_width="wrap_content" 
	    android:layout_height="wrap_content" 
	    android:text="@string/button"
	    android:id="@+id/button"
	    />
	    
	<ImageView
	 	android:layout_width="wrap_content" 
	    android:layout_height="wrap_content"
	    android:id="@+id/imageView"
	    />    

</LinearLayout>


ImageViewActivity.java

package cn.itcast.image;

import cn.itcast.service.ImageService;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageViewActivity extends Activity {
	private static final String TAG = "ImageViewActivity";
	private EditText pathText;
	private ImageView imageView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        pathText = (EditText) this.findViewById(R.id.urlpath);
        imageView = (ImageView) this.findViewById(R.id.imageView);
        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				String path = pathText.getText().toString();
				try {
					byte[] data = ImageService.getImage(path);
					Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);//生成位图
					imageView.setImageBitmap(bitmap);//显示图片	
				} catch (Exception e) {
					Toast.makeText(ImageViewActivity.this, R.string.error, 1).show();
					Log.e(TAG, e.toString());
				}
			}
		});
        
    }
}
在AndroidManifest.xml中添加网络访问权限

<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>




 显示html代码;

j2se测试代码

HtmlRequest.java

package cn.itcast.net;

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


public class HtmlRequest {
	public static void main(String[] args) throws Exception {
		//URL封装web访问路径;
		URL url = new URL("http://www.sohu.com/");
		//打开连接;
		HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5*1000);
		
		InputStream inStream = conn.getInputStream();//通过输入流获取html代码数据;
		byte[] data = readInputStream(inStream);//得到html的二进制数据
		String html = new String(data);
		System.out.println(html);
	}
	
	/**
	 * 从流里读取数据;以二进制形式返回;
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		
		int len = 0;
		while((len = inStream.read(buffer)) != -1){//没有读到末尾一直循环;
			outStream.write(buffer, 0, len);//将buffer的数据写到内存中;
		}
		
		inStream.close();
		return outStream.toByteArray();
	}
}
StreamTool.java

package cn.itcast.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {
	
	/**
	 * 从流里读取数据;以二进制形式返回;
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		
		int len = 0;
		while((len = inStream.read(buffer)) != -1){//没有读到末尾一直循环;
			outStream.write(buffer, 0, len);//将buffer的数据写到内存中;
		}
		
		inStream.close();
		return outStream.toByteArray();
	}
}

HtmlService.java

package cn.itcast.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.itcast.utils.StreamTool;

public class HtmlService {
	
	/**
	 * 返回html的二进制数据;
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static String getHtml(String path) throws Exception {
		//URL封装web访问路径;
				URL url = new URL(path);
				//打开连接;
				HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5*1000);
				
				InputStream inStream = conn.getInputStream();//通过输入流获取html代码数据;
				byte[] data = StreamTool.readInputStream(inStream);//得到html的二进制数据
				String html = new String(data);
				return html;
		
	}
}


 

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
	<ScrollView 
	    android:layout_width="fill_parent"
	     android:layout_height="fill_parent">
	    <TextView
	        android:layout_width="fill_parent"
	        android:layout_height="wrap_content"
	        android:id="@+id/textView"
	        />
	</ScrollView>    

</LinearLayout>

AndroidManifest.xml-----资源清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.itcast.html"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".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>
	<!-- 访问网络的权限 -->
	<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
MainActivity.java

package cn.itcast.html;

import cn.itcast.service.HtmlService;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private TextView textView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        textView = (TextView) this.findViewById(R.id.textView);
        try {
        	textView.setText(HtmlService.getHtml("http://www.sohu.com"));
		} catch (Exception e) {
			Log.e("MainActivity", e.toString());
			Toast.makeText(MainActivity.this, "网络连接失败", 1).show();
		}
    }
}





 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值