HttpURLConnection 传输文件
package ext.integration.k2;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import static wt.index.IndexFieldNames.contentType;
public class HttpConnectionUtil {
public static String PostUpFile(String surl,String fpath, String sysType,String filename, String user, String password, String fileid,InputStream stream) throws IOException {
//params: { method: 'BigFileUp', fpath: self.processName, sysType: self.sysType, username: 'cascobigfile', password: 'p@ssw0rd000', fileid: fileid },
URL url = null;
HttpURLConnection httpConn = null;
BufferedReader reader = null;
String viewUrl = "";
String result = "";
try {
String BOUNDARY = UUID.randomUUID().toString().replace("-", "");
url = new URL(surl);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(10000); // 设置发起连接的等待时间,10s
httpConn.setReadTimeout(300000); // 设置数据读取超时的时间,300s
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)");
String auth = user + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
String authHeader = "Basic " + new String(encodedAuth);
httpConn.setRequestProperty("Authorization", authHeader);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream os = httpConn.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"username\"").append("\r\n\r\n"); //转换类型
strBuf.append(user);
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"password\"").append("\r\n\r\n"); //是否删除源文件:0=删除,1=不删除
strBuf.append(password);
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"fileid\"").append("\r\n\r\n"); //是否删除源文件:0=删除,1=不删除
strBuf.append(fileid);
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"fpath\"").append("\r\n\r\n"); //是否删除源文件:0=删除,1=不删除
strBuf.append(fpath);
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"sysType\"").append("\r\n\r\n"); //是否删除源文件:0=删除,1=不删除
strBuf.append(sysType);
//strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
//strBuf.append("Content-Disposition: form-data; name=\"filename\"").append("\r\n\r\n"); //是否删除源文件:0=删除,1=不删除
//strBuf.append(filename);
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");
bos.write(strBuf.toString().getBytes(StandardCharsets.UTF_8));
// 开始写出文件的二进制数据
//DataInputStream in = new DataInputStream(stream);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = stream.read(bufferOut)) != -1) {
bos.write(bufferOut, 0, bytes);
}
bos.write(("\r\n--" + BOUNDARY).getBytes());
stream.close();
bos.flush();
bos.close();
os.close();
// 读取返回数据
StringBuffer strRet = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
strRet.append(line);
}
reader.close();
return strRet.toString();
} catch (Exception ex) {
System.out.print(ex.getMessage());
ex.printStackTrace();
//logger.error("-{}", ex);
} finally {
if (reader != null) {
reader = null;
}
httpConn.disconnect();
}
return null;
}
private static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
public static void inputstreamtofile(InputStream ins,File file) throws IOException {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
}
}
//调用
File file=new File("C:\\技术资料.docx");
FileInputStream stream=new FileInputStream(file);
String fileName=file.getName();
long nowTime= System.currentTimeMillis();
String fileId=String.format("%016d", nowTime);
String rst= HttpConnectionUtil.PostUpFile("http://***/FileService.asmx/Up",
"","",fileName,"", "",fileId,stream);