欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpClient的基础应用

程序员文章站 2022-07-13 12:55:33
...

HttpClient是用来发送HTTP请求的,也就是HTTP的客户端。任何HTTP请求都可以由它模拟出来。

 

1.发送GET请求:

                HttpClient httpClient = new DefaultHttpClient();
                // 初始化GET请求
                HttpGet get = new HttpGet("http://localhost:8080");
                // 执行GET请求
                HttpResponse response = httpClient.execute(get);
                // 获取请求返回的数据
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			entity = new BufferedHttpEntity(entity);
			InputStream in = entity.getContent();
			byte[] read = new byte[1024];
			byte[] all = new byte[0];
			int num;
			while ((num = in.read(read)) > 0) {
				byte[] temp = new byte[all.length + num];
				System.arraycopy(all, 0, temp, 0, all.length);
				System.arraycopy(read, 0, temp, all.length, num);
				all = temp;
			}
			System.out.println(new String(all));
			in.close();
		}
                // 一次GET请求结束
		get.abort();

 

2.发送POST请求

HttpClient httpClient = new DefaultHttpClient();
HttpPost get = new HttpPost("http://localhost:8080/xxxxxx");
//创建表单参数列表  
List<NameValuePair> qparams = new ArrayList<NameValuePair>(); 
// 添加参数
qparams.add(new BasicNameValuePair("id", "5"));
//填充表单  
get.setEntity(new UrlEncodedFormEntity(qparams,"UTF-8"));
// 执行POST请求
HttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
// ......
// 接下来就与GET一样了

 

3.自己封装请求的输入流

HttpClient httpClient = new DefaultHttpClient();
// 封装输入流
ContentProducer cp = new ContentProducer() {
	public void writeTo(OutputStream outstream) throws IOException {
		Writer writer = new OutputStreamWriter(outstream, "UTF-8");
		writer.write("write the stream by myself");
		writer.flush();
	}
};
HttpEntity requestEntity = new EntityTemplate(cp);
HttpPost httppost = new HttpPost("http://localhost:8080/xxx");
httppost.setEntity(requestEntity);
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
// 接下来与GET/POST一样了。
相关标签: HTTP HttpClient