Android读取网页内容

1、修改AndroidManifest.xml文件

<uses-permission android:name="android.permission.INTERNET" />

2、网页读取类

package com.neohope.android.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpUtils {

    public static String readStringFromUrl(String szUrl,String szCharcode) throws IOException {
        URL url = new URL(szUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");

        String szJson = "";
        int resPonseCode = conn.getResponseCode();
        if (conn.getResponseCode() == 200)
        {
            InputStream is = conn.getInputStream();
            byte[] data = readStream(is);
            szJson = new String(data,szCharcode);
        }

        return szJson;
    }

    private static byte[] readStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            bout.write(buffer, 0, len);
        }
        bout.close();
        inputStream.close();

        return bout.toByteArray();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*