3.java 关于文件
public class ReadFromFile {
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
while ((charread = reader.read(tempchars)) != -1) {
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
randomFile = new RandomAccessFile(fileName, "r");
long fileLength = randomFile.length();
int beginIndex = (fileLength > 4) ? 4 : 0;
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
2.通过URL获取文件
package test1;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class FileDown {
@SuppressWarnings("finally")
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
try {
URL url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setConnectTimeout(1000*5);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
int fileLength = httpURLConnection.getContentLength();
System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
String fileFullName = "aaa.apk";
String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[2048];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
}
bin.close();
out.close();
System.out.println("文件下载成功!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件下载失败!");
} finally {
return file;
}
}
public static void main(String[] args) {
downloadFile("http://count.liqucn.com/d.php?id=22709&urlos=android&from_type=web", "B:/myFiles/");
}
}
3.java new File(网络路径)
import java.net.URL;
public static void main(String[] args) {
try {
URL url = new URL("http://10.xxx/xxx/abc.xlsx");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"gb2312"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
4.java通过httppost请求传文件
public class MainUI {
private static final String REQUEST_PATH = "http://localhost/server_url.php";
private static final String BOUNDARY = "20140501";
public static void main(String[] args) throws Exception {
URL url = new URL(REQUEST_PATH);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(3000);
httpConn.setReadTimeout(30000);
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream os = httpConn.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
String content = "--" + BOUNDARY + "\r\n";
content += "Content-Disposition: form-data; name=\"title\"" + "\r\n\r\n";
content += "我是post数据的值";
content += "\r\n--" + BOUNDARY + "\r\n";
content += "Content-Disposition: form-data; name=\"cover_img\"; filename=\"avatar.jpg\"\r\n";
content += "Content-Type: image/jpeg\r\n\r\n";
bos.write(content.getBytes());
FileInputStream fin = new FileInputStream(new File("avatar.jpg"));
BufferedInputStream bfi = new BufferedInputStream(fin);
byte[] buffer = new byte[4096];
int bytes = bfi.read(buffer, 0, buffer.length);
while (bytes != -1) {
bos.write(buffer, 0, bytes);
bytes = bfi.read(buffer, 0, buffer.length);
}
bfi.close();
fin.close();
bos.write(("\r\n--" + BOUNDARY).getBytes());
bos.flush();
bos.close();
os.close();
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
String res = strBuf.toString();
System.out.println(res);
reader.close();
httpConn.disconnect();
}
}
5.ssp发送文件案例
package com.esint.plug.util;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import javax.activation.MimetypesFileTypeMap;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.sound.sampled.AudioFormat;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.aspectj.weaver.ast.Var;
import org.omg.IOP.Encoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.esint.plug.consts.GlobalConsts;
import com.esint.plug.enums.ResultEnums;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public final class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger("esint");
private static final String PATH_KEY = "path";
public HttpUtils() {}
private static HttpUtils httpUtils;
public HttpUtils getInstance(){
if(httpUtils == null){
httpUtils = new HttpUtils();
}
return httpUtils;
}
public interface HttpClientDownLoadProgress {
public void onProgress(int progress);
}
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
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();
Map<String, List<String>> map = connection.getHeaderFields();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, String param) {
OutputStream out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = conn.getOutputStream();
out.write(param.getBytes("UTF-8"));
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String sendPostForm(String url, Map<String,String> paramMap) {
HttpPost post = new HttpPost(url);
List<BasicNameValuePair> pairList = new ArrayList<>();
for(String key : paramMap.keySet()){
pairList.add(new BasicNameValuePair(key,paramMap.get(key)));
}
String resultData = null;
try {
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList,"utf-8");
post.setEntity(uefe);
post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
resultData = EntityUtils.toString(response.getEntity(),"utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return resultData;
}
@SuppressWarnings("rawtypes")
public static String formUploadCenter(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap, List<String> filesList,String contentType) {
String res = "";
HttpURLConnection conn = null;
String boundary = "---------------------------123821742118716";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept","application/json, text/javascript, */*");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("charsert", "utf-8");
OutputStream out = new DataOutputStream(conn.getOutputStream());
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
System.out.println("inputName------- "+inputName);
System.out.println("inputValue------- "+inputValue);
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
System.out.println("strBuf======"+strBuf);
}
if(!filesList.isEmpty()){
for (String strFilePath : filesList) {
String strPathPer = "http://file.zfw.weijingyuan.com.cn:9000/front/downfile?guid=";
String strPathLas = strFilePath.split("&")[2];
String strZFWPath = strPathPer+strPathLas;
System.out.println("strPathPer ````````````````````````````````````` "+strPathPer);
System.out.println("strPathLas ````````````````````````````````````` "+strPathLas);
System.out.println("strZFWPath ````````````````````````````````````` "+strZFWPath);
File file = new File(strZFWPath);
System.out.println("filename ===============================文件开始的方法 ------------------------------------------------------------------------------=====================");
System.out.println("filename ===================================================="+ file.getName());
System.out.println("****** file --------****//*//********"+file);
String filename = strFilePath.split("&")[1];;
System.out.println("filename------------- ******************// "+filename);
contentType = "application/octet-stream";
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
System.out.println("strBuf file======"+strBuf);
out.write(strBuf.toString().getBytes());
URL urlAttach = null;
try {
System.out.println("```````````````````````````````````````````````````````````````开始下载文件并调用上传方法```````````````````````````````````````````````````````");
urlAttach = new URL(strZFWPath);
URLConnection connection = urlAttach.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setConnectTimeout(1000 * 5);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
String fileFullName = strFilePath.split("&")[1];
String strSys = System.getProperty("user.dir");
String path =strSys+File.separatorChar +"tempFileByCenter" +File.separator+ fileFullName;
System.out.println("新路径------------------------------------------ " +path);
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out1 = new FileOutputStream(file);
String strFileName = file.getName();
System.out.println("strname === " + strFileName);
int size = 0;
int len = 0;
byte[] buf = new byte[2048];
while ((size = bin.read(buf)) != -1) {
len += size;
out1.write(buf, 0, size);
out.write(buf, 0, size);
}
bin.close();
out1.close();
System.out.println("```````````````````````````````````````````````````````````````开始下载文件并调用上传方法11111```````````````````````````````````````````````````````");
if (file.exists()) {
System.out.println("```````````````````````````````````````````````````````````````开始下载文件并调用上传方法222```````````````````````````````````````````````````````"+file +"ssss"+file.getName());
DataInputStream 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);
}
in.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
System.out.println("endData------------- "+endData);
out.write(endData);
out.flush();
out.close();
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
public static String sendPostFormUrl(String url, Map<String,String> paramMap) {
HttpPost post = new HttpPost(url);
List<BasicNameValuePair> pairList = new ArrayList<>();
for(String key : paramMap.keySet()){
pairList.add(new BasicNameValuePair(key,paramMap.get(key)));
}
String resultData = null;
try {
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList,"utf-8");
post.setEntity(uefe);
post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
resultData = EntityUtils.toString(response.getEntity(),"utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return resultData;
}
public static String sendPostJson(String url, String param) {
OutputStream out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = conn.getOutputStream();
out.write(param.getBytes("UTF-8"));
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
@SuppressWarnings("rawtypes")
public static String formUpload(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap, String contentType) {
String res = "";
HttpURLConnection conn = null;
String boundary = "---------------------------123821742118716";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
OutputStream out = new DataOutputStream(conn.getOutputStream());
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(boundary)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
}
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
String[] valueSplit = inputValue.split(",");
for (String fileStr : valueSplit) {
File file = new File(fileStr);
String filename = "";
if (file.exists()) {
filename = file.getName();
}
contentType = new MimetypesFileTypeMap().getContentType(file);
if (!"".equals(contentType)) {
if (filename.endsWith(".png")) {
contentType = "image/png";
} else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
contentType = "image/jpeg";
} else if (filename.endsWith(".gif")) {
contentType = "image/gif";
} else if (filename.endsWith(".ico")) {
contentType = "image/image/x-icon";
}
}
if (contentType == null || "".equals(contentType)) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(boundary)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"; filename=\"" + filename
+ "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
if (file.exists()) {
DataInputStream 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);
}
in.close();
}
}
}
}
byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
public static void downloadFile(String remoteFilePath, String localFilePath) {
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File file = new File(localFilePath);
try {
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(file));
int len = 2048;
byte[] bytes = new byte[len];
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static HttpServletRequest getHttpServletRequest() {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
return request;
}
public static String getLocalIp(HttpServletRequest request) {
String remoteAddr = request.getRemoteAddr();
String forwarded = request.getHeader("X-Forwarded-For");
String realIp = request.getHeader("X-Real-IP");
String ip = null;
if (realIp == null) {
if (forwarded == null) {
ip = remoteAddr;
} else {
ip = remoteAddr + "/" + forwarded.split(",")[0];
}
} else {
if (realIp.equals(forwarded)) {
ip = realIp;
} else {
if(forwarded != null){
forwarded = forwarded.split(",")[0];
}
ip = realIp + "/" + forwarded;
}
}
return ip;
}
public static void httpDownloadFile(HttpUtilsElement utilsElement) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier()
);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
HttpGet httpGet = new HttpGet(utilsElement.getUrl());
setGetHead(httpGet, utilsElement.getHeadMap());
CloseableHttpResponse response = client.execute(httpGet);
Header[] headers = response.getHeaders("Content-Disposition");
for(Header head : headers){
HeaderElement[] elements = head.getElements();
for(HeaderElement element : elements){
NameValuePair pair = element.getParameterByName("filename");
if(pair != null && StringUtils.isBlank(utilsElement.getFileName())){
utilsElement.setFileName(pair.getValue());
break;
}
}
}
if(StringUtils.isBlank(utilsElement.getRespContentType())){
Header[] contentTypes = response.getHeaders("Content-type");
for(Header head : contentTypes){
utilsElement.setRespContentType(head.getValue());
if(StringUtils.isNotBlank(utilsElement.getRespContentType()) && StringUtils.isBlank(utilsElement.getFileType())){
utilsElement.setFileType(getFileTypeByContentType(utilsElement.getRespContentType()));
break;
}
}
}else {
if(StringUtils.isBlank(utilsElement.getFileType())){
utilsElement.setFileType(getFileTypeByContentType(utilsElement.getRespContentType()));
}
}
try {
HttpEntity httpEntity = response.getEntity();
long contentLength = httpEntity.getContentLength();
InputStream inputStream = httpEntity.getContent();
HttpClientDownLoadProgress progress = new HttpClientDownLoadProgress() {
@Override
public void onProgress(int progress) {
logger.info("download progress ==> [{}]",progress);
System.out.println(progress);
}
};
PropertiesUtils utils = new PropertiesUtils("global/params.properties");
String wx_web_file_temp_path = utils.getProperty("wx_web_file_temp_path");
if(StringUtils.isBlank(wx_web_file_temp_path)){
wx_web_file_temp_path = "/tmp/fileTemp/";
}
String catalog = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + File.separator + utilsElement.getFileType();
String localPath = saveFileToLocal(inputStream, wx_web_file_temp_path + catalog, utilsElement.getFileName(), progress, contentLength);
utilsElement.setLocalPath(localPath);
logger.info("下载文件保存的路径为 ==> {}",localPath);
EntityUtils.consume(httpEntity);
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String getFileTypeByContentType(String contentType){
if (contentType.contains("image")) {
return "image";
}else if(contentType.contains("video")){
return "video";
}else if(contentType.contains("audio")){
return "voice";
}else {
return "file";
}
}
private static String saveFileToLocal(InputStream is,String fileCatalog, String fileName, HttpClientDownLoadProgress progress,Long contentLength) throws IOException {
File file = new File(fileCatalog);
if(!file.exists()){
file.mkdirs();
}
byte[] buffer = new byte[1024];
int r = 0;
long totalRead = 0;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
if (progress != null) {
progress.onProgress((int) (totalRead * 100 / contentLength));
}
}
String filePath = fileCatalog + File.separator + fileName;
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
return filePath;
}
public static Map<String,String> saveFileToFdfs(InputStream in,String fileName){
Map<String,String> map = null;
try{
PropertiesUtils utils = new PropertiesUtils("global/param_hexi.properties");
String dfs_url = utils.getProperty("file.lan.path");
String url = "";
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(dfs_url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("inputfile",in, ContentType.MULTIPART_FORM_DATA, fileName);
StringBody type1 = new StringBody("0",ContentType.TEXT_PLAIN);
builder.addPart("type", type1);
HttpEntity entity1 = builder.build();
httpPost.setEntity(entity1);
HttpResponse response1 = httpClient.execute(httpPost);
HttpEntity responseEntity = response1.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
JSONObject obj = JSONObject.fromObject(result);
if(obj.containsKey(GlobalConsts.BASE_RETURN_PARAM_KEY_RESULT_CODE) && ("" + ResultEnums.TRUE_200.getCode()).equals(obj.getString(GlobalConsts.BASE_RETURN_PARAM_KEY_RESULT_CODE))){
String resultData = obj.getString(GlobalConsts.BASE_RETURN_PARAM_KEY_RESULT_DATA);
JSONArray arr = JSONArray.fromObject(resultData);
List<Map<String,String>> list = (List<Map<String, String>>) JSONArray.toCollection(arr, Map.class);
if(list.size() > 0){
return list.get(0);
}
}
}
}catch(Exception e){
e.printStackTrace();
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return map;
}
private static 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));
}
}
}
public static void main(String[] args) {
HttpUtilsElement elem = new HttpUtilsElement();
String url = "https://zwapp.tj.gov.cn:7020/group1/M00/00/0B/Cl4Tq10XIniEG2ZgAAAAADbv9k0699.jpg?filename=magazine-unlock-01-2.3.1390-_00eb9e6723d24953a90b09d8829e57de.jpg";
elem.setUrl(url);
elem.setFileType("voice");
File file = new File("D:\\tmp\\fileTemp\\2019-07-16\\image\\1.jpg");
try {
InputStream in = new FileInputStream(file);
Map<String, String> map = saveFileToFdfs(in, "2.png");
System.out.println(map);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(elem.getFileName());
System.out.println(elem.getFileType());
System.out.println(elem.getRespContentType());
}
private static void a() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("inputfile","/Users/hancock/Downloads/14825153586.jpg");
String s = formUpload("http://mfiles.weijingyuan.com.cn/front/upload", null, map, "");
System.out.println(s);
}
public String postSSL(String url, String param){
try {
HttpClient client= ConsumerHttpClientConnectionManager.getHttpsCilentInstance();
HttpPost post=new HttpPost(url);
post.setHeader("Content-Type", "application/Json; charset=UTF-8");
StringEntity entity=new StringEntity(param, "UTF-8");
post.setEntity(entity);
HttpResponse response=client.execute(post);
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode())
{
HttpEntity res=response.getEntity();
String result= EntityUtils.toString(res);
return result;
}else{
logger.error("resultCode is {}", response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
logger.error("push error {}",e);
}
return null;
}
}