首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

经过地址得到网页内容

2012-10-29 
通过地址得到网页内容方法1:public static void main(String args[]){String urlhttp://www.baidu.com

通过地址得到网页内容
方法1:
public static void main(String args[]){
       
        String url="http://www.baidu.com";
       
        try {
            URL requestURL = new URL(url);
            InputStream inStream = requestURL.openStream();
           
            int c;
            StringBuffer sb = new StringBuffer();
            while((c=inStream.read()) != -1){
                sb.append((char)c);
            }
           
            String response = new String(sb.toString().getBytes("iso-8859-1") , "utf-8");
           
            System.out.println(response);
           
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }


方法2:可设置链接超时

package wd.com.update;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class NetworkTool {

/**
* 获取网址内容
* @param url
* @return
* @throws Exception
*/
public static String getContent(String url) throws Exception{
    StringBuilder sb = new StringBuilder();
   
    HttpClient client = new DefaultHttpClient();
    HttpParams httpParams = client.getParams();
    //设置网络超时参数
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    HttpResponse response = client.execute(new HttpGet(url));
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
       
        String line = null;
        while ((line = reader.readLine())!= null){
            sb.append(line + "\n");
        }
        reader.close();
    }
    return sb.toString();
}
}






热点排行