日期:2014-05-17 浏览次数:20727 次
1:工具类
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:业务类
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:主Activate
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(); } } }
?