1、Http文件上传、下载
1.1文件上传(有HTTP、HTTPS两种)
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class UploadTest {
private static HttpURLConnection conn = null;
private static InputStream in = null;
private static final String DEFAULT_CHARSET = "utf-8";
public static void main(String[] args) throws Exception {
String url = "http://127.0.0.1:8080/upload";
String body = "{\n" +
" \"AA\": {\n" +
" \"BB\": \"123123123123\",\n" +
" \"CC\":\"1\"\n" +
" }\n" +
"}";
List<String> fileList = new ArrayList<>();
fileList.add("155.pdf");
fileList.add("116.pdf");
fileList.add("b21f95a9eeecbba7a6693e83caed31c.jpg");
fileList.add("001.txt");
sends(body, fileList, url, null);
receives();
}
public static void main(String[] args) throws Exception {
String url = "https://127.0.0.1:8080/upload";
String body = "{\n" +
" \"AA\": {\n" +
" \"BB\": \"123123123123\",\n" +
" \"CC\":\"1\"\n" +
" }\n" +
"}";
List<String> fileList = new ArrayList<>();
fileList.add("155.pdf");
fileList.add("116.pdf");
fileList.add("b21f95a9eeecbba7a6693e83caed31c.jpg");
fileList.add("001.txt");
sends(body, fileMap, url, new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)));
receives();
}
public static void sends(String body,List<String> fileList, String urlString, Proxy proxy) throws Exception {
OutputStream out = null;
try {
URL url = new URL(urlString);
if (null != proxy) {
System.out.println("===================代理================");
SslUtil.ignoreSsl();
conn = (HttpURLConnection) url.openConnection(proxy);
} else {
conn = (HttpURLConnection) url.openConnection();
}
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(15 * 1000);
conn.setRequestMethod("POST");
String end = "\r\n";
String twoHyphens = "--";
String boundary = "--------------------------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
out = new DataOutputStream(conn.getOutputStream());
if (null != body && !"".equals(body)) {
StringBuilder sd = new StringBuilder();
sd.append(twoHyphens + boundary + end);
sd.append("Content-Disposition: form-data; name=\"params\"" + end + end);
sd.append(body);
sd.append(end);
out.write(sd.toString().getBytes());
}
for (int i = 0; i < fileList.size(); i++) {
StringBuilder fileSd = new StringBuilder();
String fileName = fileList.get(i);
fileSd.append(twoHyphens + boundary + end);
fileSd.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
fileName) + end + end);
out.write(fileSd.toString().getBytes());
write(out, "C:\\Users\\Administrator\\Desktop\\" + fileName);
out.write(end.getBytes());
}
out.write((twoHyphens + boundary + twoHyphens + end).getBytes());
out.flush();
} catch (IOException e) {
throw e;
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
throw e;
}
}
}
}
public static void write(OutputStream out, String filePath) throws IOException {
File file = new File(filePath);
DataInputStream in = null;
try {
in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
} catch (Exception e) {
throw e;
} finally {
in.close();
}
}
public static void receives() throws IOException {
String charset = getResponseCharset(conn.getContentType());
byte[] rbuf = null;
InputStream es = conn.getErrorStream();
try {
in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "ISO8859-1"));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
rbuf = buffer.toString().getBytes("ISO8859-1");
} catch (UnsupportedEncodingException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
if (es != null) {
try {
es.close();
} catch (IOException e) {
throw e;
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
throw e;
}
}
if (conn != null) {
conn.disconnect();
}
}
String res = new String(rbuf);
System.out.println("receive:\n" + res);
}
private static String getResponseCharset(String ctype) {
String charset = DEFAULT_CHARSET;
if (null != ctype && !"".equals(ctype)) {
String[] params = ctype.split(";");
for (String param : params) {
param = param.trim();
if (param.startsWith("charset")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
if (null != pair[1] && !"".equals(pair[1])) {
charset = pair[1].trim();
}
}
break;
}
}
}
return charset;
}
}
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class SslUtil {
private static void trustAllHttpsCertificates() {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
} catch (Exception e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager,X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
}
public static CloseableHttpClient createSSLClientDefault(){
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){
public boolean isTrusted(X509Certificate[] chain,String authType) 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();
}
public static void ignoreSsl() throws Exception{
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}
1.2 Http文件下载
public static String download(String fileName, String downloadUrl, String savePath) throws Exception {
long begin = System.currentTimeMillis();
File file = new File(savePath);
File path = file.getParentFile();
if (!path.exists()) {
path.mkdirs();
}
URL url = new URL(downloadUrl);
URLConnection con = null;
InputStream is = null;
FileOutputStream os = null;
File sf = null;
try {
System.out.println("文件下载请求URL[%s],文件存放路径[%s]", url, localFilePath);
con = url.openConnection();
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty("Connection", "keep-alive");
HttpUtil.setReqHeader(con, fileName);
//设置请求超时为15s
con.setConnectTimeout(15 * 1000);
is = con.getInputStream();
byte[] getData = HttpUtil.readInputStream(is);
os = new FileOutputStream(path);
// 开始读取
os.write(getData);
} catch (IOException ie) {
System.out.println("io异常:%s", ie.getMessage());
throw ie;
} catch (Exception e) {
System.out.println("文件下载异常:%s", e.getMessage());
throw e;
} finally {
if (null != os) {
os.close();
}
if (null != is) {
is.close();
}
}
long end = System.currentTimeMillis();
System.out.println("文件下载耗时:" + (end - begin) / 1000 + "s");
return localFilePath;
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
String logFile = PubUtil.getLogFile();
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
} catch (IOException e) {
TrcLog.info(logFile, "IO异常:%s", e.getMessage());
throw e;
} finally {
if (null != bos) {
bos.close();
}
}
return bos.toByteArray();
}