Java:使用HttpClient进行POST和GET请求以及文件下载

1.HttpClient

大家可以先看一下HttpClient的介绍,这篇博文写的还算不错:http://blog.csdn.net/wangpeng047/article/details/19624529

当然,详细的文档,你可以去官方网站查看和下载:http://hc.apache.org/httpclient-3.x/

2.本博客简单介绍一下POST和GET以及文件下载的应用。

代码如下:

package net.mobctrl;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @web http://www.mobctrl.net
 * @author Zheng Haibo
 * @Description: 文件下载 POST GET
 */
public class HttpClientUtils {

	/**
	 * 最大线程池
	 */
	public static final int THREAD_POOL_SIZE = 5;

	public interface HttpClientDownLoadProgress {
		public void onProgress(int progress);
	}

	private static HttpClientUtils httpClientDownload;

	private ExecutorService downloadExcutorService;

	private HttpClientUtils() {
		downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
	}

	public static HttpClientUtils getInstance() {
		if (httpClientDownload == null) {
			httpClientDownload = new HttpClientUtils();
		}
		return httpClientDownload;
	}

	/**
	 * 下载文件
	 *
	 * @param url
	 * @param filePath
	 */
	public void download(final String url, final String filePath) {
		downloadExcutorService.execute(new Runnable() {

			@Override
			public void run() {
				httpDownloadFile(url, filePath, null,null);
			}
		});
	}

	/**
	 * 下载文件
	 *
	 * @param url
	 * @param filePath
	 * @param progress
	 *            进度回调
	 */
	public void download(final String url, final String filePath,
			final HttpClientDownLoadProgress progress) {
		downloadExcutorService.execute(new Runnable() {

			@Override
			public void run() {
				httpDownloadFile(url, filePath, progress,null);
			}
		});
	}

	/**
	 * 下载文件
	 *
	 * @param url
	 * @param filePath
	 */
	private void httpDownloadFile(String url, String filePath,
			HttpClientDownLoadProgress progress, Map<String, String> headMap) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpGet httpGet = new HttpGet(url);
			setGetHead(httpGet, headMap);
			CloseableHttpResponse response1 = httpclient.execute(httpGet);
			try {
				System.out.println(response1.getStatusLine());
				HttpEntity httpEntity = response1.getEntity();
				long contentLength = httpEntity.getContentLength();
				InputStream is = httpEntity.getContent();
				// 根据InputStream 下载文件
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				byte[] buffer = new byte[4096];
				int r = 0;
				long totalRead = 0;
				while ((r = is.read(buffer)) > 0) {
					output.write(buffer, 0, r);
					totalRead += r;
					if (progress != null) {// 回调进度
						progress.onProgress((int) (totalRead * 100 / contentLength));
					}
				}
				FileOutputStream fos = new FileOutputStream(filePath);
				output.writeTo(fos);
				output.flush();
				output.close();
				fos.close();
				EntityUtils.consume(httpEntity);
			} finally {
				response1.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * get请求
	 *
	 * @param url
	 * @return
	 */
	public String httpGet(String url) {
		return httpGet(url, null);
	}

	/**
	 * http get请求
	 *
	 * @param url
	 * @return
	 */
	public String httpGet(String url, Map<String, String> headMap) {
		String responseContent = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response1 = httpclient.execute(httpGet);
			setGetHead(httpGet, headMap);
			try {
				System.out.println(response1.getStatusLine());
				HttpEntity entity = response1.getEntity();
				InputStream is = entity.getContent();
				StringBuffer strBuf = new StringBuffer();
				byte[] buffer = new byte[4096];
				int r = 0;
				while ((r = is.read(buffer)) > 0) {
					strBuf.append(new String(buffer, 0, r, "UTF-8"));
				}
				responseContent = strBuf.toString();
				System.out.println("debug:" + responseContent);
				EntityUtils.consume(entity);
			} finally {
				response1.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseContent;
	}

	public String httpPost(String url, Map<String, String> paramsMap) {
		return httpPost(url, paramsMap, null);
	}

	/**
	 * http的post请求
	 *
	 * @param url
	 * @param paramsMap
	 * @return
	 */
	public String httpPost(String url, Map<String, String> paramsMap,
			Map<String, String> headMap) {
		String responseContent = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			setPostHead(httpPost, headMap);
			setPostParams(httpPost, paramsMap);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				System.out.println(response.getStatusLine());
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				StringBuffer strBuf = new StringBuffer();
				byte[] buffer = new byte[4096];
				int r = 0;
				while ((r = is.read(buffer)) > 0) {
					strBuf.append(new String(buffer, 0, r, "UTF-8"));
				}
				responseContent = strBuf.toString();
				EntityUtils.consume(entity);
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("responseContent = " + responseContent);
		return responseContent;
	}

	/**
	 * 设置POST的参数
	 *
	 * @param httpPost
	 * @param paramsMap
	 * @throws Exception
	 */
	private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)
			throws Exception {
		if (paramsMap != null && paramsMap.size() > 0) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Set<String> keySet = paramsMap.keySet();
			for (String key : keySet) {
				nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		}
	}

	/**
	 * 设置http的HEAD
	 *
	 * @param httpPost
	 * @param headMap
	 */
	private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
		if (headMap != null && headMap.size() > 0) {
			Set<String> keySet = headMap.keySet();
			for (String key : keySet) {
				httpPost.addHeader(key, headMap.get(key));
			}
		}
	}

	/**
	 * 设置http的HEAD
	 *
	 * @param httpGet
	 * @param headMap
	 */
	private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
		if (headMap != null && headMap.size() > 0) {
			Set<String> keySet = headMap.keySet();
			for (String key : keySet) {
				httpGet.addHeader(key, headMap.get(key));
			}
		}
	}
}

我们可以使用如下代码进行测试:

import java.util.HashMap;
import java.util.Map;

import net.mobctrl.HttpClientUtils;
import net.mobctrl.HttpClientUtils.HttpClientDownLoadProgress;

/**
 * @date 2015年1月14日 下午1:49:50
 * @author Zheng Haibo
 * @Description: 测试
 */
public class Main {

	public static void main(String[] args) {
		/**
		 * 测试下载文件 异步下载
		 */
		HttpClientUtils.getInstance().download(
				"http://newbbs.qiniudn.com/phone.png", "test.png",
				new HttpClientDownLoadProgress() {

					@Override
					public void onProgress(int progress) {
						System.out.println("download progress = " + progress);
					}
				});

		// POST 同步方法
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", "admin");
		params.put("password", "admin");
		HttpClientUtils.getInstance().httpPost(
				"http://localhost:8080/sshmysql/register", params);

		// GET 同步方法
		HttpClientUtils.getInstance().httpGet(
				"http://wthrcdn.etouch.cn/weather_mini?city=北京");

	}

}

运行结果为:

HTTP/1.1 200 OK
responseContent = {"id":"-2","msg":"添加失败!用户名已经存在!"}
HTTP/1.1 200 OK
debug:{"desc":"OK","status":1000,"data":{"wendu":"-1","ganmao":"天气转凉,空气湿度较大,较易发生感冒,体质较弱的朋友请注意适当防护。","forecast":[{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 2℃","type":"小雪","low":"低温 -5℃","date":"14日星期三"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 3℃","type":"霾","low":"低温 -3℃","date":"15日星期四"},{"fengxiang":"北风","fengli":"4-5级","high":"高温 5℃","type":"晴","low":"低温 -6℃","date":"16日星期五"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 4℃","type":"多云","low":"低温 -5℃","date":"17日星期六"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 6℃","type":"多云","low":"低温 -4℃","date":"18日星期天"}],"yesterday":{"fl":"微风","fx":"无持续风向","high":"高温 4℃","type":"霾","low":"低温 -4℃","date":"13日星期二"},"aqi":"309","city":"北京"}}
HTTP/1.1 200 OK
download progress = 2
download progress = 6
download progress = 8
download progress = 10
download progress = 12
download progress = 15
download progress = 17
download progress = 20
download progress = 22
download progress = 27
download progress = 29
download progress = 31
download progress = 33
download progress = 36
download progress = 38
download progress = 40
download progress = 45
download progress = 47
download progress = 49
download progress = 51
download progress = 54
download progress = 56
download progress = 58
download progress = 60
download progress = 62
download progress = 69
download progress = 75
download progress = 81
download progress = 87
download progress = 89
download progress = 91
download progress = 93
download progress = 96
download progress = 100

下载过程有进度回调。

相关的libs包,可以在如下链接中下载:http://download.csdn.net/detail/nuptboyzhb/8362801

上述代码,既可以在J2SE,J2EE中使用,也可以在Android中使用,在android中使用时,需要相关的权限。

未经允许不得用于商业目的

时间: 2024-10-23 13:25:28

Java:使用HttpClient进行POST和GET请求以及文件下载的相关文章

java中httpclient实现digest验证的请求

1.首先介绍如何使用HttpClient发起GET和POST请求   GET 方式: //先将参数放入List,再对参数进行URL编码 List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("param1", "中国")); params.add(new BasicNameValuePa

Java学习心得之 HttpClient的GET和POST请求

作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 Java学习心得之 HttpClient的GET和POST请求 1. 前言2. GET请求3. POST请求 一.前言 本篇博文记录了HttpClient的GET和POST请求 本文内容基于以下文章: http://huangqiqing123.iteye.com/blog/2054436        (HttpClient之 addHeader与setHeader)http://zyw

java中HttpClient的使用

HttpClient的使用步骤: 1.使用Apache的HttpClient发送GET和POST请求的步骤如下: 1. 使用帮助类HttpClients创建CloseableHttpClient对象. 2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例. 3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数. 4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进Http

Java中httpClient中三种超时设置

本文章给大家介绍一下关于Java中httpClient中的三种超时设置小结 在Apache的HttpClient包中,有三个设置超时的地方: /* 从连接池中取连接的超时时间*/ ConnManagerParams.setTimeout(params, 1000); /*连接超时*/ HttpConnectionParams.setConnectionTimeout(params, 2000); /*请求超时*/ HttpConnectionParams.setSoTimeout(params,

JAVA使用apache http组件发送POST请求

在上一篇文章中,使用了JDK中原始的HttpURLConnection向指定URL发送POST请求 可以看到编码量有些大,并且使用了输入输出流 传递的参数还是用“name=XXX”这种硬编的字符串进行传递的 下面介绍一下apache commons项目中的apache http组件中的HttpClient 用这种方式可以很快的使用键值对参数向URL发送请求 package com.newflypig.demo; /** * 使用apache http组件提供的HttpClient向URL发送PO

Java通过httpclient获取cookie模拟登录

package Step1; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpc

Java发布webservice应用并发送SOAP请求调用

webservice框架有很多,比如axis.axis2.cxf.xFire等等,做服务端和做客户端都可行,个人感觉使用这些框架的好处是减少了对于接口信息的解析,最主要的是减少了对于传递于网络中XML的解析,代价是你不得不在你的框架中添加对于这些框架的依赖.个人观点是:服务端使用这些框架还行,如果做客户端,没必要使用这些框架,只需使用httpclient即可. 一.创建并发布一个简单的webservice应用 1.webservice 代码: import javax.jws.WebMethod

HttpClient发送get,post接口请求

HttpClient发送get post接口请求 /** * post * @param url POST地址 * @param data POST数据NameValuePair[] * @return 响应的参数 */ public static String post(String url,NameValuePair[] data){---------------get里面没有data只有url String response = ""; HttpClient httpClient

java 通过httpclient调用https 的webapi

java如何通过httpclient 调用采用https方式的webapi?如何验证证书.示例:https://devdata.osisoft.com/p...需要通过httpclient调用该接口,没有做过https 方式的调用不知道怎么解决. java 通过httpclient调用https 的webapi >> csharp 这个答案描述的挺清楚的:http://www.goodpm.net/postreply/csharp/1010000008927916/java通过httpclie