`
chenpenghui
  • 浏览: 37876 次
  • 性别: Icon_minigender_1
  • 来自: 台州
社区版块
存档分类
最新评论

httpClient的使用

    博客分类:
  • JAVA
 
阅读更多

httpClient的简单使用方法(代理方式的)。
package HttpClientDemo;

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

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientDemo1 {
	public static void method() throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet("http://www.baidu.com");//相当于在地址栏输入网址
		HttpHost proxy = new HttpHost("proxy.zj.********.com", 8080, "http");//设置代理
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
				proxy);//设置成默认代理
		HttpResponse response = httpClient.execute(httpGet);//执行这次访问,得到response
		Header[] headers = httpGet.getAllHeaders();
		System.out.println("headers.length : " + headers.length);//得到头
		if (headers.length > 0) {
			for (int i = 0; i < headers.length; i++) {
				System.out.println("headers[" + i + "] : " + headers[i]);
			}
		}
		HttpEntity entity = response.getEntity();//得到content
		System.out.println("entity : " + entity);
		BufferedReader br = new BufferedReader(new InputStreamReader(entity
				.getContent(), "GBK"));//得到content里的东西
		String line = null;
		while ((line = br.readLine()) != null) {
			System.out.println(line.toString());
		}
		br.close();
		httpGet.abort();//free
	}

	public static void main(String[] args) throws Exception {
		method();//测一把
	}

}
 
 
  • 大小: 13.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics