java 利用原生URLConnection 双向认证get,post请求文件,down下载
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
/**
* @author admin
* @Description https双向认证
* get 普通参数
* post可以上传参数
*/
public class HttpsClientUtil {
public static String KEY_STORE_FILE="客户.p12";
public static String KEY_STORE_PASS="客户.p12密码";
public static String TRUST_STORE_FILE="服务端_truststore.jks";
public static String TRUST_STORE_PASS="服务端密码.";
private static SSLContext sslContext;
public static void main(String[] args) {
// 下载文件测试
downloadFile("http://localhost:8080/suncicigifts/20161203000.txt", "F:/home/hxbank");
}
/**
*
* @param urlPath
* 下载路径
* @param downloadDir
* 下载存放目录
* @return 返回下载文件
*/
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
BufferedInputStream bin = null;
OutputStream out = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
if(httpURLConnection instanceof HttpsURLConnection){
((HttpsURLConnection)httpURLConnection)
.setSSLSocketFactory(getSSLContext().getSocketFactory());
}
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 文件名
String filePathUrl = httpURLConnection.getURL().getFile();
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
System.out.println("file length---->" + fileLength+"file filePathUrl---->" + filePathUrl);
bin = new BufferedInputStream(httpURLConnection.getInputStream());
String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 打印下载百分比
System.out.println("下载了-------> " + len * 100 / fileLength +"%\n");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(bin!=null){
try {
bin.close();
} catch (IOException e) {
}
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
}
}
}
return file;
}
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param actionUrl 访问的服务器URL
* @param params 普通参数
* @param files 文件参数
* @return
* @throws IOException
*/
public static String postFile(String actionUrl, Map<String, String> params, Map<String, File> files) {
StringBuilder resp = new StringBuilder();
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
try{
System.out.println("url:"+actionUrl);
URL realUrl = new URL(actionUrl);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
if(conn instanceof HttpsURLConnection){
((HttpsURLConnection)conn)
.setSSLSocketFactory(getSSLContext().getSocketFactory());
}
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
if(params!=null){
for (Map.Entry<String, String> entry : params.entrySet()){
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}//end for
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
BufferedReader in = null;
// 发送文件数据
if (files != null) {
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
// name是post中传参的键 filename是文件的名称
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}
if(is!=null){
is.close();
}
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 定义 BufferedReader输入流来读取URL的响应
if(conn.getResponseCode()==200){
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(),"utf-8"));
}else{
in = new BufferedReader(new InputStreamReader(
conn.getErrorStream(),"utf-8"));
}
String line;
while ((line = in.readLine()) != null) {
resp.append(line);
}
outStream.close();
conn.disconnect();
}// end if (files != null)
}catch (Exception e) {
System.out.println("发送postFile请求出现异常!" + e);
e.printStackTrace();
}
return resp.toString();
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL 含参数
* @return URL 所代表远程资源的响应结果
*
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
System.out.println("url:"+url);
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
// 打开和URL之间的连接
if(connection instanceof HttpsURLConnection){
((HttpsURLConnection)connection)
.setSSLSocketFactory(getSSLContext().getSocketFactory());
}
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
if(connection.getResponseCode()==200){
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"utf-8"));
}else{
in = new BufferedReader(new InputStreamReader(
connection.getErrorStream(),"utf-8"));
}
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
private static SSLContext getSSLContext(){
long time1=System.currentTimeMillis();
if(sslContext==null){
try {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(getkeyStore(),KEY_STORE_PASS.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(getTrustStore());
TrustManager[] trustManagers= trustManagerFactory.getTrustManagers();
sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
long time2=System.currentTimeMillis();
System.out.println("SSLContext 初始化时间:"+(time2-time1));
return sslContext;
}
private static KeyStore getkeyStore(){
KeyStore keySotre=null;
try {
keySotre = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(new File(KEY_STORE_FILE));
keySotre.load(fis, KEY_STORE_PASS.toCharArray());
fis.close();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return keySotre;
}
private static KeyStore getTrustStore() throws IOException{
KeyStore trustKeyStore=null;
FileInputStream fis=null;
try {
trustKeyStore=KeyStore.getInstance("JKS");
fis = new FileInputStream(new File(TRUST_STORE_FILE));
trustKeyStore.load(fis, TRUST_STORE_PASS.toCharArray());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
fis.close();
}
return trustKeyStore;
}
}
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
/**
* @author admin
* @Description https双向认证
* get 普通参数
* post可以上传参数
*/
public class HttpsClientUtil {
public static String KEY_STORE_FILE="客户.p12";
public static String KEY_STORE_PASS="客户.p12密码";
public static String TRUST_STORE_FILE="服务端_truststore.jks";
public static String TRUST_STORE_PASS="服务端密码.";
private static SSLContext sslContext;
public static void main(String[] args) {
// 下载文件测试
downloadFile("http://localhost:8080/suncicigifts/20161203000.txt", "F:/home/hxbank");
}
/**
*
* @param urlPath
* 下载路径
* @param downloadDir
* 下载存放目录
* @return 返回下载文件
*/
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
BufferedInputStream bin = null;
OutputStream out = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
if(httpURLConnection instanceof HttpsURLConnection){
((HttpsURLConnection)httpURLConnection)
.setSSLSocketFactory(getSSLContext().getSocketFactory());
}
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 文件名
String filePathUrl = httpURLConnection.getURL().getFile();
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
System.out.println("file length---->" + fileLength+"file filePathUrl---->" + filePathUrl);
bin = new BufferedInputStream(httpURLConnection.getInputStream());
String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 打印下载百分比
System.out.println("下载了-------> " + len * 100 / fileLength +"%\n");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(bin!=null){
try {
bin.close();
} catch (IOException e) {
}
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
}
}
}
return file;
}
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param actionUrl 访问的服务器URL
* @param params 普通参数
* @param files 文件参数
* @return
* @throws IOException
*/
public static String postFile(String actionUrl, Map<String, String> params, Map<String, File> files) {
StringBuilder resp = new StringBuilder();
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
try{
System.out.println("url:"+actionUrl);
URL realUrl = new URL(actionUrl);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
if(conn instanceof HttpsURLConnection){
((HttpsURLConnection)conn)
.setSSLSocketFactory(getSSLContext().getSocketFactory());
}
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
if(params!=null){
for (Map.Entry<String, String> entry : params.entrySet()){
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}//end for
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
BufferedReader in = null;
// 发送文件数据
if (files != null) {
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
// name是post中传参的键 filename是文件的名称
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}
if(is!=null){
is.close();
}
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 定义 BufferedReader输入流来读取URL的响应
if(conn.getResponseCode()==200){
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(),"utf-8"));
}else{
in = new BufferedReader(new InputStreamReader(
conn.getErrorStream(),"utf-8"));
}
String line;
while ((line = in.readLine()) != null) {
resp.append(line);
}
outStream.close();
conn.disconnect();
}// end if (files != null)
}catch (Exception e) {
System.out.println("发送postFile请求出现异常!" + e);
e.printStackTrace();
}
return resp.toString();
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL 含参数
* @return URL 所代表远程资源的响应结果
*
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
System.out.println("url:"+url);
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
// 打开和URL之间的连接
if(connection instanceof HttpsURLConnection){
((HttpsURLConnection)connection)
.setSSLSocketFactory(getSSLContext().getSocketFactory());
}
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
if(connection.getResponseCode()==200){
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"utf-8"));
}else{
in = new BufferedReader(new InputStreamReader(
connection.getErrorStream(),"utf-8"));
}
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
private static SSLContext getSSLContext(){
long time1=System.currentTimeMillis();
if(sslContext==null){
try {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(getkeyStore(),KEY_STORE_PASS.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(getTrustStore());
TrustManager[] trustManagers= trustManagerFactory.getTrustManagers();
sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
long time2=System.currentTimeMillis();
System.out.println("SSLContext 初始化时间:"+(time2-time1));
return sslContext;
}
private static KeyStore getkeyStore(){
KeyStore keySotre=null;
try {
keySotre = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(new File(KEY_STORE_FILE));
keySotre.load(fis, KEY_STORE_PASS.toCharArray());
fis.close();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return keySotre;
}
private static KeyStore getTrustStore() throws IOException{
KeyStore trustKeyStore=null;
FileInputStream fis=null;
try {
trustKeyStore=KeyStore.getInstance("JKS");
fis = new FileInputStream(new File(TRUST_STORE_FILE));
trustKeyStore.load(fis, TRUST_STORE_PASS.toCharArray());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
fis.close();
}
return trustKeyStore;
}
}