HttpClient读取某个网址返回的内容

需要的核心Jar文件

 httpclient-4.0.1.jar:http://apache.freelamp.com/httpcomponents/httpclient/binary/httpcomponents-client-4.0.1-bin.zip
 httpcore-4.0.1.jar:http://apache.freelamp.com/httpcomponents/httpcore/binary/httpcomponents-core-4.0.1-bin.zip

 

Java测试代码:

 

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class ReadingWebContent {
	/**
	 * 返回内容字符串
	 * **/
	public static String getContent(String url) throws Exception{
		String backContent = null;
		//先建立一个客户端实例,将模拟一个浏览器
		HttpClient httpclient = null;
		HttpGet httpget = null;
		try {
			//************************************************************
			// 设置超时时间
			// 创建 HttpParams 以用来设置 HTTP 参数
			HttpParams params = new BasicHttpParams();
			// 设置连接超时和 Socket 超时,以及 Socket 缓存大小
			HttpConnectionParams.setConnectionTimeout(params, 180 * 1000);
			HttpConnectionParams.setSoTimeout(params, 180 * 1000);
			HttpConnectionParams.setSocketBufferSize(params, 8192);
			// 设置重定向,缺省为 true
			HttpClientParams.setRedirecting(params, false);
			//************************************************************   
			httpclient = new DefaultHttpClient(params);
//			httpclient = new DefaultHttpClient();
			// 建立一个get方法请求,提交刷新
			httpget = new HttpGet(url);		
			
			HttpResponse response = httpclient.execute(httpget); 
			//HttpStatus.SC_OK(即:200)服务器收到并理解客户端的请求而且正常处理了
//			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
//				//对象呼叫中止
//				httpget.abort();
//				backContent = "获取不到";
//			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {            
			    //start 读取整个页面内容
			    InputStream is = entity.getContent();
			    BufferedReader in = new BufferedReader(new InputStreamReader(is)); 
			    StringBuffer buffer = new StringBuffer(); 
			    String line = "";
			    while ((line = in.readLine()) != null) {
			    	buffer.append(line);
			    }
			    //end 读取整个页面内容
			    backContent = buffer.toString();
			}
		} catch (Exception e) {
			httpget.abort();
			backContent = "有异常,获取不到";	
			System.out.println("-------------异常开始");
			e.printStackTrace();
			System.out.println("-------------异常结束");
		}finally{
			//HttpClient的实例不再需要时,降低连接,管理器关闭,以确保立即释放所有系统资源
			if(httpclient != null)
				httpclient.getConnectionManager().shutdown();
		}        
        //返回结果
        return backContent;
	}
	
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws Exception{
		ReadingWebContent a = new ReadingWebContent();
		System.out.println(a.getContent("http://www.google.com"));
	}
}

 

在Java中,可以使用Apache HttpClient库来发送HTTP请求并处理响应。如果你需要接受上一个接口的响应来进行下一步的操作,通常你会按照这样的步骤进行: 1. **创建HttpClient实例**: 首先,你需要导入`org.apache.http.client.HttpClient`和相关的依赖。例如: ```java import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; ``` 2. **发起请求**: 使用`HttpGet`创建一个HTTP GET请求,并设置目标URL。如果之前接口返回的是某个特定资源的地址,那么这里就应该是那个地址: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("previous_api_response_url"); ``` 3. **发送请求并获取响应**: 然后通过`CloseableHttpClient`的execute方法发送请求并获取`HttpResponse`: ```java HttpResponse response = httpClient.execute(httpGet); ``` 4. **解析响应**: 根据HTTP状态码检查响应是否成功(比如200表示成功),然后使用如`EntityUtils.toString(response.getEntity())`将响应内容读取成字符串或进一步解析成JSON等: ```java int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_OK) { String responseBody = EntityUtils.toString(response.getEntity()); // 对responseBody进行后续处理 } else { // 处理错误情况 } ``` 5. **关闭连接**: 最后别忘了关闭`CloseableHttpClient`以释放资源: ```java httpClient.close(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值