从网络上获取网页源代码

来源:互联网 发布:ubuntu光盘安装教程 编辑:程序博客网 时间:2024/05/16 14:36
package cn.itcast.htmlviewer;import cn.itcast.htmlviewer.service.NetUtil;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;public class DemoActivity extends Activity implements OnClickListener {private EditText mEtAddress;private Button mBtView;private TextView mTvView;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        mBtView =   (Button) this.findViewById(R.id.bt_view);        mEtAddress =  (EditText) this.findViewById(R.id.et_address);        mTvView =  (TextView) this.findViewById(R.id.tv_content);        mBtView.setOnClickListener(this);                    }@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.bt_view://按钮对应的点击事件 String address = mEtAddress.getText().toString().trim();if("".equals(address)){Toast.makeText(this, "地址不能为空", Toast.LENGTH_SHORT).show();return;}try {String html = NetUtil.getHtml(address);mTvView.setText(html);} catch (Exception e) {e.printStackTrace();Toast.makeText(this, "获取数据失败", 0).show();}break;}}}
<pre class="java" name="code">package cn.itcast.htmlviewer.util;import java.io.ByteArrayOutputStream;import java.io.InputStream;public class StreamTool {/** * 把一个inputstream里面的内容转化成一个byte[]  */public static byte[] getBytes(InputStream is) throws Exception{ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while((len = is.read(buffer))!=-1){bos.write(buffer, 0, len);}is.close();bos.flush();byte[] result = bos.toByteArray();System.out.println(new String(result));return  result;}}
<pre class="java" name="code">package cn.itcast.htmlviewer.service;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import cn.itcast.htmlviewer.util.StreamTool;public class NetUtil {public static String getHtml(String address) throws Exception {URL url = new URL(address);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(5000);conn.setRequestMethod("GET");int code = conn.getResponseCode();if (code == 200) {InputStream is = conn.getInputStream();byte[] result = StreamTool.getBytes(is);String temp = new String(result);// 简单描述原理// 真实的代码需要解析meta里面的信息if (temp.contains("gbk")) {return new String(result, "gb2312");} else {return temp;}} else {throw new IllegalStateException("访问网络失败");}}}



0 0
原创粉丝点击