通过地址得到网页内容

方法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();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值