package com.smartdoer.utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.web.multipart.MultipartFile;
public class HttpPostUtil {
URL url;
HttpURLConnection conn;
String boundary = "--------";
Map<String, String> textParams = new HashMap<String, String>();
List<MultipartFile> fileparams = new ArrayList<MultipartFile>();
List<File> fileList = new ArrayList<File>();
List<String> urlList = new ArrayList<String>();
DataOutputStream ds;
public HttpPostUtil(String url) throws Exception {
this.url = new URL(url);
}
public void setUrl(String url) throws Exception {
this.url = new URL(url);
}
public void addTextParameter(String name, String value) {
textParams.put(name, value);
}
public void addFileParameter(MultipartFile value) {
fileparams.add(value);
}
public void addFileList(File value){
fileList.add(value);
}
public void addUrlList(String str){
urlList.add(str);
}
public void clearAllParameters() {
textParams.clear();
fileparams.clear();
}
public String send() throws Exception {
StringBuffer result = new StringBuffer();
initConnection();
try {
conn.connect();
} catch (SocketTimeoutException e) {
throw new RuntimeException();
}
ds = new DataOutputStream(conn.getOutputStream());
writeFileParams();
writeStringParams();
writeFileList();
writeUrlList();
paramsEnd();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),
"utf-8"));
String line = "";
while ((line = in.readLine()) != null) {
result.append(line).append("
");
}
conn.disconnect();
return result.toString();
}
private void initConnection() throws Exception {
conn = (HttpURLConnection) this.url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
}
private void writeStringParams() throws Exception {
Set<String> keySet = textParams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
ds.writeBytes("--" + boundary + "
");
ds.writeBytes("Content-Disposition: form-data; name="" + name + ""
");
ds.writeBytes("
");
ds.writeBytes(encode(value) + "
");
}
}
private void writeFileParams() throws Exception {
String name = "upload";
for (MultipartFile file : fileparams) {
MultipartFile value = file;
ds.writeBytes("--" + boundary + "
");
ds.writeBytes("Content-Disposition: form-data; name="" + name
+ ""; filename="" + encode(value.getOriginalFilename()) + ""
");
ds.writeBytes("Content-Type: " + getContentType(value) + "
");
ds.writeBytes("
");
ds.write(getBytes(value));
ds.writeBytes("
");
}
}
private void writeFileList() throws Exception {
String name = "upload";
for (File file : fileList) {
File value = file;
ds.writeBytes("--" + boundary + "
");
ds.writeBytes("Content-Disposition: form-data; name="" + name
+ ""; filename="" + encode(value.getName()) + ""
");
ds.writeBytes("Content-Type: image
");
ds.writeBytes("
");
ds.write(getBytes(value));
ds.writeBytes("
");
}
}
private void writeUrlList() throws Exception {
String name = "upload";
for (String strUrl : urlList) {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
DataInputStream input = new DataInputStream(conn.getInputStream());
DataOutputStream output = new DataOutputStream(new FileOutputStream(strUrl.substring(strUrl.lastIndexOf("/") + 1).toUpperCase()));
byte[] buffer = new byte[1024 * 8 * 1000];
int count = 0;
count = input.read(buffer);
ds.writeBytes("--" + boundary + "
");
ds.writeBytes("Content-Disposition: form-data; name="" + name
+ ""; filename="" + encode(strUrl) + ""
");
ds.writeBytes("Content-Type: image
");
ds.writeBytes("
");
ds.write(buffer);
ds.writeBytes("
");
output.close();
input.close();
}
}
private String getContentType(MultipartFile f) throws Exception {
return "image";
}
private byte[] getBytes(MultipartFile f) throws Exception {
InputStream is = f.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = is.read(b)) != -1) {
out.write(b, 0, n);
}
is.close();
return out.toByteArray();
}
private byte[] getBytes(File f) throws Exception {
FileInputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
private void paramsEnd() throws Exception {
ds.writeBytes("--" + boundary + "--" + "
");
ds.writeBytes("
");
}
private String encode(String value) throws Exception{
return URLEncoder.encode(value, "UTF-8");
}
public static void main(String[] args) throws Exception {
String postData = "{"id":"212","title":"测试1","content":"测试1","author":"测试1","createtime":"2016-3-4 15:25:16"}";
String postUrl="http://localhost:81/qmcg/admin/interData/webSiteCase/outSideDataImp";
HttpPostUtil u = new HttpPostUtil(postUrl);
u.addUrlList("http://127.0.0.1:81/pirImg/upload/Image/201608/20160826152343638.png");
String result = u.send();
System.out.println("result:"+result);
}
}
开始时,上传图片正常,后来无意间发现有一些图片上传失败,报的错误为ByteArrayInputStream不能转化成FileInputStream,
后来发现,是因为图片太小的事,大图片没有问题,经过修改后是这样

图片中红框内注释的为以前的代码。