android 获取网页源代码,Android开发 通过URL获取网页源代码(滚动显示)

layout

*注意TextView滚动条的实现

MainActivity

package com.test.URLtest;

import android.app.Activity;

import android.os.Bundle;

import android.os.StrictMode;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends Activity {

private EditText pathText;

private TextView codeView;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

Button button = (Button) this.findViewById(R.id.button);

pathText = (EditText) this.findViewById(R.id.url);

codeView = (TextView) this.findViewById(R.id.codeView);

button.setOnClickListener(new ButtonClickListener());

}

private final class ButtonClickListener implements View.OnClickListener{

@Override

public void onClick(View v){

String path = pathText.getText().toString();

try {

String html = PageService.getHtml(path);

codeView.setText(html);

}

catch(Exception e){

e.printStackTrace();

Toast.makeText(getApplicationContext(),R.string.error,Toast.LENGTH_SHORT).show();

}

}

}

}

PageService业务类

package com.test.URLtest;

import javax.net.ssl.HttpsURLConnection;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

/**

* Created by 宝冬 on 2015/7/9.

*/

public class PageService {

public static String getHtml(String path) throws Exception{

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");

if(conn.getResponseCode()==200){

InputStream inStream = conn.getInputStream();

byte[] data = StreamTool.read(inStream);

String html = new String(data,"UTF-8");

return html;

}

return null;

}

}

StreamTool工具类

package com.test.URLtest;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

public class StreamTool {

/*

* 读取流中的数据

* */

public static byte[] read(InputStream inStream) throws Exception {

ByteArrayOutputStream outStream =new ByteArrayOutputStream();

byte[] buffer = new byte[9999];

int len = 0;

while ((len = inStream.read(buffer)) != -1)//读取流中的数据

{

outStream.write(buffer,0,len);

}

inStream.close();

return outStream.toByteArray();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值