日期:2014-05-17 浏览次数:20719 次
1:StreamTool
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); } inStream.close(); return outStream.toByteArray(); } }
?
2:HtmlService
package cn.itcast.service; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import cn.itcast.utils.StreamTool; public class HtmlService { public static String getHtml(String path) throws Exception { 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, "gb2312"); return html; } }
?3:MainActivity
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 { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView 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(); } } }
?4:
<?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"> - <application android:icon="@drawable/icon" 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-sdk android:minSdkVersion="8" /> - <!-- 访问网络的权限 --> <uses-permission android:name="android.permission.INTERNET" /> </manifest>
?