Android学习笔记---24_网络通信之网页源码查看器

24_网络通信之网页源码查看器

2013-03-18
24_网络通信之网页源码查看器
------------------------------------
1.界面:一个输入text框,输入一个网页的地址,点击查看后,再下面的<TextView>控件
  显示,如果内容较多,需要显示滚动条。
----------------------------------------------
2.Http watch可以用这个工具来查看http协议封装的信息。
-------------------------------------------------------
2013-03-19
------------------------
3.从internet获取数据的相关知识:
  从Internet获取数据
-----------------------------------
利用HttpURLConnection对象,我们可以从网络中获取网页数据.
URL url = new URL(" http://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);//设置连接超时
conn.setRequestMethod(“GET”);//以get方式发起请求
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//得到网络返回的输入流
String result = readData(is, "GBK");
conn.disconnect();
//第一个参数为输入流,第二个参数为字符集编码
public static String readData(InputStream inSream, String charsetName) throws 

Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}
-----------------------------------------------------
4.利用HttpURLConnection对象,我们可以从网络中获取文件数据.
URL url = new URL(" http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();
readAsFile(is, "Img269812337.jpg"); 

public static void readAsFile(InputStream inSream, File file) throws Exception{
FileOutputStream outStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
  outStream.close();
inSream.close();
}
------------------------------------------------
5.需要在清单文件中加入的权限:
<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
----------------------------------------------------------------------
6.24_网络通信之网页源码查看器的代码:
----------------------------------------
  a.新建项目:HtmlViewer
    /HtmlViewer/src/com/credream/htmlviewer/HtmlViewerActivity.java
--------------
package com.credream.htmlviewer;


import com.credream.service.PageService;
import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.SimpleAdapter.ViewBinder;

import android.widget.Toast;


public class HtmlViewerActivity extends Activity {

  private EditText pathText;
 
 private TextView codeView;
/** Called when the activity is first created. */
  
  @Override
   
 public void onCreate(Bundle savedInstanceState) {
   
     super.onCreate(savedInstanceState);
    
    setContentView(R.layout.main);
  
 pathText=(EditText)this.findViewById(R.id.pagepath);
 
  codeView=(TextView)this.findViewById(R.id.codeview);
 
 Button button=(Button) this.findViewById(R.id.button);
  

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,1).show();

}

 

}

}
}
-------------------------------------------------------------------------------
  b./HtmlViewer/src/com/credream/service/PageService.java
--------------------------------------------------------------
package com.credream.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.credream.util.StreamTool;

public class PageService
{
/**
 * 获取网页的HTml代码
 */

public static String getHtml(String path) throws Exception
{
URL uri = new URL(path);
HttpURLConnection conn = (HttpURLConnection) uri.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;
}

}
---------------------------------------------------------------------------
c./HtmlViewer/src/com/credream/util/StreamTool.java
-----------------------------------------------------
package com.credream.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * 读取流中的数据
 * 
 * @author xiaofeng
 * 
 */
public class StreamTool
{
public static byte[] read(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();
}

}
----------------------------------------------------------------------
d./HtmlViewer/res/layout/main.xml
---------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/pagepath" />
<EditText 
     android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=" http://192.168.1.110:6118/web/index.html"
   android:id="@+id/pagepath"
    />

<Button
 android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button"
android:id="@+id/button"
/>
<!--
        <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/codeview" />-->
<ScrollView 
     android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    >
      <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/codeview" />
</ScrollView>
</LinearLayout>
------------------------------------------------------
e./HtmlViewer/res/values/strings.xml
-------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, HtmlViewerActivity!</string>
    <string name="app_name">Html源码查看</string>
       <string name="pagepath">网页路径</string>
       <string name="button">查看</string>
             <string name="error">读取信息错误</string>

</resources>
---------------------------------------------------
f./HtmlViewer/AndroidManifest.xml
---------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=" http://schemas.android.com/apk/res/android"
    package="com.credream.htmlviewer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".HtmlViewerActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <!-- 访问网络权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>
----------------------------------------------------------------------
7.新建web项目,并且在webroot下,新建文件index.html
---------------------------------------------------
/web/WebContent/index.html
--------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 

" http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
创梦网络<br/>
//Http watch
</body>
</html>
----------------------------------------------------------------------

你可能感兴趣的:(Android学习笔记---24_网络通信之网页源码查看器)