Android获取网络上的网页代码

public void showhtml(View v) {
        String path = pathText.getText().toString();
        try {
            String html = HtmlService.getHtml(path);
            textView.setText(html);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), R.string.error, Toast.LENGTH_LONG).show();
        }
    }

以下是编写的HTMLService网页代码的业务类

package com.zhoujn.internet.service;

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

import com.wangjialin.internet.utils.StreamTool;

public class HtmlService {
    /**
     * 获取网页源码
     * @param path 网页路径
     * @return
     */
    public static String getHtml(String path) throws Exception {
        HttpURLConnection conn = (HttpURLConnection)new URL(path).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == 200){
            InputStream inStream = conn.getInputStream();
            byte[] data = StreamTool.read(inStream);
            return new String(data);
        }
        return null;
    }
}

编写把流转化为数组的工具类:StreamTool

package com.zhoujn.internet.utils;

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

public class StreamTool {

    /**
     * 从流中读取数据
     * @param inStream
     * @return
     */
    public static byte[] read(InputStream inStream) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        inStream.close();
        return outputStream.toByteArray();
    }


}

注意,需要配置AndroidManifest.xml
因为要访问网络,所以需要加入网络访问权限,



你可能感兴趣的:(服务器,Android开发)