一、使用HttpURLConnection,实现get,post,put,delete,upload,download静态方法
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
* HttpURLConnection封装工具类
*
* @author CHHuang
*
*/
public class HttpUtil {
public static final String SERVLET_POST = "POST" ;
public static final String SERVLET_GET = "GET" ;
public static final String SERVLET_DELETE = "DELETE" ;
public static final String SERVLET_PUT = "PUT" ;
public static final String UTF_8 = "UTF-8" ;
public static final String CONTENT_TYPE = "Content-Type";
public static final String CHARSET = "Charset";
public static final String CONNECTION = "Connection";
public static final String REFERER = "Referer";
private static final String ACCEPT = "Accept";
private static final String RANGE = "Range";
private static final int TIME_OUT = 10000;
private static final String PREFIX = "--";
private static final String LINE_END = "\r\n";
public static final String BOUNDARY = "*****";
public static final String TEXT_PLAIN= "text/plain; charset=utf-8";
public static final String KEEP_ALIVE = "Keep-Alive";
public static final String MULTIPAT_FORMDATA= "multipart/form-data; boundary=" + BOUNDARY;
private static final String ACCEPT_VALUE = "*/*";
/**
* 拼接请求参数
*
* @param paramMap
* @return
*/
public static String prepareParam(Map<String,Object> paramMap){
StringBuffer sb = new StringBuffer();
if(paramMap==null || paramMap.isEmpty()){
return null ;
}else{
for(String key: paramMap.keySet()){
String value = (String)paramMap.get(key);
if(sb.length()<1){
sb.append(key).append("=").append(value);
}else{
sb.append("&").append(key).append("=").append(value);
}
}
return sb.toString();
}
}
/**
* post提交数据
*
* @param urlStr
* @param paramMap
* @return
* @throws Exception
*/
public static HttpURLConnection doPost(String urlStr, Map<String,Object> params, Map<String,String> propertys) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(SERVLET_POST);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(TIME_OUT);
/*setRequestProperty*/
conn.setRequestProperty(CONTENT_TYPE, TEXT_PLAIN);
if (propertys!=null && !propertys.isEmpty()){
for (String key : propertys.keySet()) {
conn.setRequestProperty(key, propertys.get(key));
}
}
/*设置参数*/
String paramStr = prepareParam(params);
if(paramStr!=null && !"".equals(paramStr)){
OutputStream os = conn.getOutputStream();
os.write(paramStr.toString().getBytes(UTF_8));
os.flush();
os.close();
}
return conn;
}
/**
* get提交数据
*
* @param urlStr
* @param paramMap
* @return
* @throws Exception
*/
public static HttpURLConnection doGet(String urlStr, Map<String,Object> params, Map<String,String> propertys) throws IOException{
/*设置参数*/
String paramStr = prepareParam(params);
if(paramStr!=null && !"".equals(paramStr)){
urlStr +="?"+paramStr;
}
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(SERVLET_GET);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(TIME_OUT);
/*setRequestProperty*/
conn.setRequestProperty(CONTENT_TYPE, TEXT_PLAIN);
if (propertys!=null && !propertys.isEmpty()){
for (String key : propertys.keySet()) {
conn.setRequestProperty(key, propertys.get(key));
}
}
return conn;
}
/**
* put提交数据
*
* @param urlStr
* @param paramMap
* @return
* @throws Exception
*/
public static HttpURLConnection doPut(String urlStr, Map<String,Object> params, Map<String,String> propertys) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(SERVLET_PUT);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(TIME_OUT);
/*setRequestProperty*/
conn.setRequestProperty(CONTENT_TYPE, TEXT_PLAIN);
if (propertys!=null && !propertys.isEmpty()){
for (String key : propertys.keySet()) {
conn.setRequestProperty(key, propertys.get(key));
}
}
/*设置参数*/
String paramStr = prepareParam(params);
if(paramStr!=null && !"".equals(paramStr)){
OutputStream os = conn.getOutputStream();
os.write(paramStr.toString().getBytes(UTF_8));
os.flush();
os.close();
}
return conn;
}
/**
* delete提交数据
*
* @param urlStr
* @param paramMap
* @return
* @throws IOException
* @throws Exception
*/
public static HttpURLConnection doDelete(String urlStr, Map<String,Object> params, Map<String,String> propertys) throws IOException{
/*设置参数*/
String paramStr = prepareParam(params);
if(paramStr!=null && !"".equals(paramStr)){
urlStr +="?"+paramStr;
}
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(SERVLET_DELETE);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(TIME_OUT);
/*setRequestProperty*/
conn.setRequestProperty(CONTENT_TYPE, TEXT_PLAIN);
if (propertys!=null && !propertys.isEmpty()){
for (String key : propertys.keySet()) {
conn.setRequestProperty(key, propertys.get(key));
}
}
return conn;
}
/**
* 上传文件 及 提交参数
*
* @param uploadUrl
* @param files
* @param params
* @param propertys
* @return
* @throws IOException
*/
public static HttpURLConnection doUpload(String uploadUrl, Map<String,File> files, Map<String,Object> params, Map<String,String> propertys) throws IOException {
URL url = new URL(uploadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(TIME_OUT);
/* 设置传送的method=POST */
conn.setRequestMethod(SERVLET_POST);
/* setRequestProperty */
if (propertys!=null && !propertys.isEmpty()){
for (String key : propertys.keySet()) {
conn.setRequestProperty(key, propertys.get(key));
}
}
conn.setRequestProperty(CONNECTION, KEEP_ALIVE);
conn.setRequestProperty(CHARSET, UTF_8);
conn.setRequestProperty(CONTENT_TYPE,MULTIPAT_FORMDATA);
/* 设置DataOutputStream */
DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
/* 拼接参数 */
if(params!=null && !params.isEmpty()){
for(String key : params.keySet()){
ds.writeBytes(PREFIX + BOUNDARY + LINE_END);
ds.write(("Content-Disposition: form-data;" + "name=\"" + key + "\"" + LINE_END).getBytes(UTF_8));
ds.writeBytes(LINE_END);
ds.write(params.get(key).toString().getBytes(UTF_8));
ds.writeBytes(LINE_END);
}
}
/* 拼接文件 */
if (files!=null && !files.isEmpty()){
for (String key : files.keySet()) {
ds.writeBytes(PREFIX + BOUNDARY + LINE_END);
ds.write(("Content-Disposition: form-data;" + "name=\"" + key + "\";filename=\"" + files.get(key).getName() + "\"" + LINE_END).getBytes(UTF_8));
ds.writeBytes(LINE_END);
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(files.get(key));
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据至缓冲区 */
while ((length = fStream.read(buffer)) != -1) {
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(LINE_END);
fStream.close();
}
ds.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
}
/* close streams */
ds.flush();
ds.close();
return conn;
}
/**
* 下载文件
*
* @param downloadUrl
* @param filePath
* @param params
* @param propertys
* @return
* @throws IOException
*/
public static HttpURLConnection doDownload(String downloadUrl, Map<String,Object> params, Map<String,String> propertys) throws IOException{
/*设置参数*/
String paramStr = prepareParam(params);
if(paramStr!=null && !"".equals(paramStr)){
downloadUrl +="?"+paramStr;
}
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(SERVLET_GET);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(TIME_OUT);
/*setRequestProperty*/
if (propertys!=null && !propertys.isEmpty()){
for (String key : propertys.keySet()) {
conn.setRequestProperty(key, propertys.get(key));
}
}
conn.setRequestProperty(REFERER, url.toString());
conn.setRequestProperty(CHARSET, UTF_8);
conn.setRequestProperty(ACCEPT, ACCEPT_VALUE);
conn.setRequestProperty(CONNECTION, KEEP_ALIVE);
conn.setRequestProperty(RANGE, "bytes=0-");//从第几字节到第几个字节
return conn;
}
/**
* 获取返回内容
*
* @param conn
* @return
* @throws IOException
*/
public static String getString(HttpURLConnection conn) throws IOException{
InputStream in = conn.getInputStream();
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
int n;
while ((n = in.read(b))!= -1){
out.append(new String(b,0,n));
}
in.close();
return out.toString();
}
/**
* 获取返回byte[]
*
* @param conn
* @return
* @throws IOException
*/
public static byte[] getBytes(HttpURLConnection conn) throws IOException{
InputStream in = conn.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = in.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/**
* 获取返回文件
*
* @param conn
* @param filePath
* @return
* @throws IOException
*/
public static File getFile(HttpURLConnection conn, String filePath) throws IOException{
/*下载文件*/
InputStream in = conn.getInputStream();
RandomAccessFile rf = new RandomAccessFile(filePath,"rw");
rf.seek(0);
byte[] b = new byte[204800];
int n;
while((n=in.read(b,0,1024)) > 0){
rf.write(b,0,n);
}
rf.close();
in.close();
/*返回文件*/
return new File(filePath);
}
/**
* test
* @param args
*/
// public static void main(String[] args) {
// HttpURLConnection conn = null;
// try {
// Map<String, Object> params = new HashMap<String, Object>();
// params.put("token", "760");
// params.put("title", "你好1");
// params.put("content", "你好2");
// params.put("tickerText", "你好3");
// conn = doGet("http://localhost:8080/ising/DDPush/push.app", params, null);
// conn = doPost("http://localhost:8080/ising/DDPush/ppush.app", params, null);
//
// Map<String, File> files = new HashMap<String, File>();
// files.put("file1", new File("C:/Users/HuangChen/Desktop/软件测试题答案.docx"));
// conn = doUpload("http://localhost:8080/ising/file/upload.app", files, params,null);
// conn = doDownload("http://localhost:8080/ising/file/download/5799bc4cc61c84a4deabd8fe.docx", null, null);
// conn = doDelete("http://localhost:8080/ising/file/delete/5799bc4cc61c84a4deabd8fe.app", null, null);
// if(conn!=null){
// if(conn.getResponseCode()==200){
// System.out.println(getString(conn));
// System.out.println(getBytes(conn));
// System.out.println(getFile(conn,"C:/Users/HuangChen/Desktop/test.docx"));
// }else{
// System.out.println(conn.getResponseCode());
// System.out.println(conn.getResponseMessage());
// }
// }
// conn.disconnect();
// } catch (IOException e) {
// e.printStackTrace();
// }finally{
// if(conn != null)
// conn.disconnect();
// }
// }
}
二、使用HttpClients,实现get,post,put,delete,upload,download静态方法,并且支持https
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import com.chhuang.utils.file.FileUtil;
/**
*
* @author CHHuang
*
*/
public class HttpClientUtil {
private HttpClientUtil() {
}
public static final String HTTPS = "https";
public static final String APPLICATION_JSON = "application/json";
public static final String TEXT_PLAIN = "text/plain";
public static final String SET_COOKIE = "Set-Cookie";
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_LANGUAGE = "Content-Language";
public static final String QUESTION = "?";
public static final String AND = "&";
public static final String POINT = ".";
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
public boolean isTrusted(
java.security.cert.X509Certificate[] arg0,
String arg1) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
/**
*
* @param url
* @param params
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static ResponseBean post(String url,
List<BasicNameValuePair> params, Header[] headers)
throws ClientProtocolException, IOException {
// 创建默认的httpClient实例.
CloseableHttpClient httpClient = null;
if (url.toLowerCase().startsWith(HTTPS)) {
httpClient = createSSLClientDefault();
} else {
httpClient = HttpClients.createDefault();
}
// 创建httppost
HttpPost httpPost = new HttpPost(url);
if (headers != null && headers.length > 0) {
httpPost.setHeaders(headers);
}
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params,
Consts.UTF_8));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, Consts.UTF_8);
ResponseBean responseBean = new ResponseBean(response.getAllHeaders(),
response.getLocale(), response.getProtocolVersion(),
response.getStatusLine(), result);
response.close();
httpClient.close();
return responseBean;
}
/**
*
* @param url
* @param json
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static ResponseBean post(String url, JSONObject json,
Header[] headers) throws ClientProtocolException, IOException {
// 创建默认的httpClient实例.
CloseableHttpClient httpClient = null;
if (url.toLowerCase().startsWith(HTTPS)) {
httpClient = createSSLClientDefault();
} else {
httpClient = HttpClients.createDefault();
}
// 创建httppost
HttpPost httpPost = new HttpPost(url);
if (headers != null && headers.length > 0) {
httpPost.setHeaders(headers);
}
if (json != null) {
StringEntity entity = new StringEntity(json.toString(),
Consts.UTF_8);
entity.setContentType(APPLICATION_JSON);
httpPost.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, Consts.UTF_8);
ResponseBean responseBean = new ResponseBean(response.getAllHeaders(),
response.getLocale(), response.getProtocolVersion(),
response.getStatusLine(), result);
response.close();
httpClient.close();
return responseBean;
}
/**
*
* @param url
* @param params
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static ResponseBean get(String url, List<BasicNameValuePair> params,
Header[] headers) throws ClientProtocolException, IOException {
// 创建默认的httpClient实例.
CloseableHttpClient httpClient = null;
if (url.toLowerCase().startsWith(HTTPS)) {
httpClient = createSSLClientDefault();
} else {
httpClient = HttpClients.createDefault();
}
// 创建httpGet
HttpGet httpGet = new HttpGet(url);
if (headers != null && headers.length > 0) {
httpGet.setHeaders(headers);
}
if (params != null) {
String param = URLEncodedUtils.format(params,
Consts.UTF_8);
if (url.lastIndexOf(QUESTION) == -1) {
url += QUESTION + param;
} else {
url += AND + param;
}
}
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, Consts.UTF_8);
ResponseBean responseBean = new ResponseBean(response.getAllHeaders(),
response.getLocale(), response.getProtocolVersion(),
response.getStatusLine(), result);
response.close();
httpClient.close();
return responseBean;
}
/**
*
* @param url
* @param parts
* @param headers
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public static ResponseBean upload(String url, Map<String, ContentBody> parts, Header[] headers)
throws ClientProtocolException, IOException{
// 创建默认的httpClient实例.
CloseableHttpClient httpClient = null;
if (url.toLowerCase().startsWith(HTTPS)) {
httpClient = createSSLClientDefault();
} else {
httpClient = HttpClients.createDefault();
}
// 把一个普通参数和文件上传给下面这个地址 是一个servlet
HttpPost httpPost = new HttpPost(url);
if (headers != null && headers.length > 0) {
httpPost.setHeaders(headers);
}
if(parts!=null && !parts.isEmpty()){
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(Consts.UTF_8);
Iterator<Entry<String, ContentBody>> iter = parts.entrySet().iterator();
while (iter.hasNext()) {
builder.addPart(iter.next().getKey(), iter.next().getValue());
}
httpPost.setEntity(builder.build());
}
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, Consts.UTF_8);
ResponseBean responseBean = new ResponseBean(response.getAllHeaders(),
response.getLocale(), response.getProtocolVersion(),
response.getStatusLine(), result);
// 销毁
EntityUtils.consume(entity);
response.close();
httpClient.close();
return responseBean;
}
/**
*
* @param url
* @param file
* @param headers
* @throws IOException
* @throws ClientProtocolException
*/
public static ResponseBean download(String url, File file, Header[] headers)
throws ClientProtocolException, IOException{
// 创建默认的httpClient实例.
CloseableHttpClient httpClient = null;
if (url.toLowerCase().startsWith(HTTPS)) {
httpClient = createSSLClientDefault();
} else {
httpClient = HttpClients.createDefault();
}
HttpGet httpGet = new HttpGet(url);
if (headers != null && headers.length > 0) {
httpGet.setHeaders(headers);
}
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
ResponseBean responseBean = new ResponseBean(response.getAllHeaders(),
response.getLocale(), response.getProtocolVersion(),
response.getStatusLine(), null);
InputStream in = entity.getContent();
FileUtil.makeFilePath(file);
FileOutputStream fout = new FileOutputStream(file);
int l = -1;
byte[] tmp = new byte[4096];
while ((l = in.read(tmp)) != -1) {
fout.write(tmp, 0, l);
}
fout.flush();
fout.close();
in.close();
response.close();
httpClient.close();
return responseBean;
}
}
封装的response
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
/**
* 在HttpClientUtil中使用
* responseBean
*
* @author CHHuang
*
*/
public class ResponseBean {
private Header[] headers;
private Locale locale;
private ProtocolVersion protocolVersion;
private StatusLine statusLine;
private String result;
public ResponseBean() {
super();
}
public ResponseBean(Header[] headers, Locale locale,
ProtocolVersion protocolVersion, StatusLine statusLine,
String result) {
super();
this.headers = headers;
this.locale = locale;
this.protocolVersion = protocolVersion;
this.statusLine = statusLine;
this.result = result;
}
public Header[] getHeaders() {
return headers;
}
public Header[] getHeaders(String name) {
Header[] nameHeaders = null;
if(StringUtils.isNotBlank(name) && headers!=null && headers.length>0){
List<Header> nameHeaderList = new LinkedList<Header>();
for(Header header : headers){
if(name.equalsIgnoreCase(header.getName())){
nameHeaderList.add(header);
}
}
nameHeaders = (Header[]) nameHeaderList.toArray(new Header[nameHeaderList.size()]);
}
return nameHeaders;
}
public void setHeaders(Header[] headers) {
this.headers = headers;
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public ProtocolVersion getProtocolVersion() {
return protocolVersion;
}
public void setProtocolVersion(ProtocolVersion protocolVersion) {
this.protocolVersion = protocolVersion;
}
public StatusLine getStatusLine() {
return statusLine;
}
public void setStatusLine(StatusLine statusLine) {
this.statusLine = statusLine;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}