在android上用HttpURLConnection获取网页内容

来源:互联网 发布:udid定制源码 编辑:程序博客网 时间:2024/06/07 21:45

界面效果如下,在编辑框中输入网址,点击按钮后,获取编辑框中的网址,打开HttpURLConnection连接,并获取输入流,将返回的流保存为html文件,然后再用WebView将html文件显示出来。



主要代码GetHtml.java(完整代码GetHtml.7z

package ckl.gethtml;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.webkit.WebView;import android.widget.Button;import android.widget.EditText;public class GetHtml extends Activity {private EditText mEdit = null;private Button mButton = null;private WebView mWeb = null;    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                mEdit = (EditText)findViewById(R.id.myEdit1);        mButton = (Button)findViewById(R.id.myButton1);        mWeb = (WebView)findViewById(R.id.myWeb1);                mWeb.getSettings().setJavaScriptEnabled(true);        mWeb.getSettings().setPluginsEnabled(true);                mButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {String strUrl = mEdit.getText().toString();String strFile = "/sdcard/test.html";if (!strUrl.startsWith("http://")) {strUrl = "http://" + strUrl;}getStaticPageByBytes(strUrl, strFile);mWeb.loadUrl("file://" + strFile);}});    }    private void getStaticPageByBytes(String surl, String strFile){Log.i("getStaticPageByBytes", surl + ", " + strFile);HttpURLConnection connection = null;InputStream is = null;File file = new File(strFile);FileOutputStream fos = null;try {URL url = new URL(surl);connection = (HttpURLConnection)url.openConnection();int code = connection.getResponseCode();if (HttpURLConnection.HTTP_OK == code) {connection.connect();is = connection.getInputStream();fos = new FileOutputStream(file);int i;while((i = is.read()) != -1){fos.write(i);  }is.close();fos.close();}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (connection != null) {connection.disconnect();}}}}


下面这个网页上说的方法并不能每次都能获得正确的网页内容:

http://kaoshi.china.com/java/learning/618001-1.htm 

主要是因为受到网页内容编码(encoding)的影响,页面编码内容的编码是不确定的,可能不是utf-8。

因为在java内部是使用utf-16来表示字符的,所以在使用String保存页面内容时,会被转换为utf-16来保存,写入文件时在转换为操作系统中的默认编码,

这样导致保存文件内容的编码和html中指定的编码不一致,导致中文乱码。


另外关于InputStream.available()解释如下:

“返回此输入流方法的下一个调用方可以不受阻塞地从此输入流读取(或跳过)的字节数”
如果这是一个Socket的InputStream,那么它的read方法就可能导致阻塞(即表示read方法可能一直等待对方发送的数据而不返回)
available根本不是表示这个流有多长的意思,对于Socket之类的InputStream根本无法判断这个流会有多长。

原创粉丝点击