大家可以先看一下HttpClient的介绍,这篇博文写的还算不错:/wangpeng047/article/details/19624529
当然,详细的文档,你可以去官方网站查看和下载://
2.本博客简单介绍一下POST和GET以及文件下载的应用。
代码如下:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* @web
* @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 = (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) {
(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) {
(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 = ();
try {
HttpGet httpGet = new HttpGet(url);
setGetHead(httpGet, headMap);
CloseableHttpResponse response1 = (httpGet);
try {
(());
HttpEntity httpEntity = ();
long contentLength = ();
InputStream is = ();
// 根据InputStream 下载文件
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int r = 0;
long totalRead = 0;
while ((r = (buffer)) > 0) {
(buffer, 0, r);
totalRead += r;
if (progress != null) {// 回调进度
((int) (totalRead * 100 / contentLength));
}
}
FileOutputStream fos = new FileOutputStream(filePath);
(fos);
();
();
();
(httpEntity);
} finally {
();
}
} catch (Exception e) {
();
} finally {
try {
();
} catch (IOException e) {
();
}
}
}
/**
* 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 = ();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = (httpGet);
setGetHead(httpGet, headMap);
try {
(());
HttpEntity entity = ();
responseContent = getRespString(entity);
("debug:" + responseContent);
(entity);
} finally {
();
}
} catch (Exception e) {
();
} finally {
try {
();
} catch (IOException e) {
();
}
}
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 = ();
try {
HttpPost httpPost = new HttpPost(url);
setPostHead(httpPost, headMap);
setPostParams(httpPost, paramsMap);
CloseableHttpResponse response = (httpPost);
try {
(());
HttpEntity entity = ();
responseContent = getRespString(entity);
(entity);
} finally {
();
}
} catch (Exception e) {
();
} finally {
try {
();
} catch (IOException e) {
();
}
}
("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 && () > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = ();
for (String key : keySet) {
(new BasicNameValuePair(key, (key)));
}
(new UrlEncodedFormEntity(nvps));
}
}
/**
* 设置http的HEAD
*
* @param httpPost
* @param headMap
*/
private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
if (headMap != null && () > 0) {
Set<String> keySet = ();
for (String key : keySet) {
(key, (key));
}
}
}
/**
* 设置http的HEAD
*
* @param httpGet
* @param headMap
*/
private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
if (headMap != null && () > 0) {
Set<String> keySet = ();
for (String key : keySet) {
(key, (key));
}
}
}
/**
* 上传文件
*
* @param serverUrl
* 服务器地址
* @param localFilePath
* 本地文件路径
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public String uploadFileImpl(String serverUrl, String localFilePath,
String serverFieldName, Map<String, String> params)
throws Exception {
String respStr = null;
CloseableHttpClient httpclient = ();
try {
HttpPost httppost = new HttpPost(serverUrl);
FileBody binFileBody = new FileBody(new File(localFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
.create();
// add the file params
(serverFieldName, binFileBody);
// 设置上传的其他参数
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = ();
(reqEntity);
CloseableHttpResponse response = (httppost);
try {
(());
HttpEntity resEntity = ();
respStr = getRespString(resEntity);
(resEntity);
} finally {
();
}
} finally {
();
}
("resp=" + respStr);
return respStr;
}
/**
* 设置上传文件时所附带的其他参数
*
* @param multipartEntityBuilder
* @param params
*/
private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
Map<String, String> params) {
if (params != null && () > 0) {
Set<String> keys = ();
for (String key : keys) {
multipartEntityBuilder
.addPart(key, new StringBody((key),
ContentType.TEXT_PLAIN));
}
}
}
/**
* 将返回结果转化为String
*
* @param entity
* @return
* @throws Exception
*/
private String getRespString(HttpEntity entity) throws Exception {
if (entity == null) {
return null;
}
InputStream is = ();
StringBuffer strBuf = new StringBuffer();
byte[] buffer = new byte[4096];
int r = 0;
while ((r = (buffer)) > 0) {
(new String(buffer, 0, r, "UTF-8"));
}
return ();
}
}
我们可以使用如下代码进行测试:
import ;
import ;
import ;
import ;
import ;
/**
* @date 2015年1月14日 下午1:49:50
* @author Zheng Haibo
* @Description: 测试
*/
public class Main {
public static void main(String[] args) {
/**
* 测试下载文件 异步下载
*/
().download(
"/", "",
new HttpClientDownLoadProgress() {
@Override
public void onProgress(int progress) {
("download progress = " + progress);
}
});
// POST 同步方法
Map<String, String> params = new HashMap<String, String>();
("username", "admin");
("password", "admin");
().httpPost(
"http://192.168.31.183:8080/SSHMySql/register", params);
// GET 同步方法
().httpGet(
"/weather_mini?city=北京");
// 上传文件 POST 同步方法
try {
Map<String,String> uploadParams = new LinkedHashMap<String, String>();
("userImageContentType", "image");
("userImageFileName", "");
().uploadFileImpl(
"http://192.168.31.183:8080/SSHMySql/upload", "android_bug_1.png",
"userImage", uploadParams);
} catch (Exception e) {
();
}
}
}
运行结果为:
HTTP/1.1 200 OK
responseContent = {"id":"-2","msg":"添加失败!用户名已经存在!"}
HTTP/1.1 200 OK
download progress = 6
download progress = 11
download progress = 13
download progress = 20
download progress = 22
download progress = 26
download progress = 31
download progress = 33
download progress = 35
download progress = 38
download progress = 40
download progress = 42
download progress = 44
download progress = 49
download progress = 53
download progress = 55
download progress = 57
download progress = 60
download progress = 62
download progress = 64
download progress = 66
download progress = 71
download progress = 77
download progress = 77
download progress = 80
download progress = 82
HTTP/1.1 200 OK
debug:{"desc":"OK","status":1000,"data":{"wendu":"3","ganmao":"昼夜温差很大,易发生感冒,请注意适当增减衣服,加强自我防护避免感冒。","forecast":[{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 6℃","type":"晴","low":"低温 -6℃","date":"22日星期四"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 6℃","type":"多云","low":"低温 -3℃","date":"23日星期五"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 5℃","type":"多云","low":"低温 -3℃","date":"24日星期六"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 5℃","type":"阴","low":"低温 -2℃","date":"25日星期天"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 4℃","type":"多云","low":"低温 -2℃","date":"26日星期一"}],"yesterday":{"fl":"3-4级","fx":"北风","high":"高温 5℃","type":"晴","low":"低温 -6℃","date":"21日星期三"},"aqi":"124","city":"北京"}}
download progress = 84
download progress = 86
download progress = 88
download progress = 91
download progress = 93
download progress = 95
download progress = 99
download progress = 100
HTTP/1.1 200 OK
resp={"error_code":2000,"msg":"OK","filepath":"uploadfiles/192.168.31.72_android_bug_1.png"}
下载过程有进度回调。
相关的libs包,可以在如下链接中下载:/detail/nuptboyzhb/8362801
上述代码,既可以在J2SE,J2EE中使用,也可以在Android中使用,在android中使用时,需要相关的权限。
另外,测试所使用的Web项目为:/nuptboyzhb/SSHMySQLDemo
未经允许不得用于商业目的