import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
------------------第一种上传方法开始------------------------
private static HttpClientResult finaldoUpload(String url, InputStream in, String filename) throws ClientProtocolException, IOException{
CloseableHttpClient httpclient = null;
try {
httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
//第三个参数是文件名
builder.addBinaryBody("file", in, ContentType.create("multipart/form-data"), filename);
//构建请求参数 普通表单项
// StringBody stringBody = new StringBody("12",ContentType.MULTIPART_FORM_DATA);
// builder.addPart("id",stringBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
// 执行post请求.
CloseableHttpResponse response = httpclient.execute(post);
try {
if (response.getStatusLine().getStatusCode() == 200) {
// 获取响应实体
HttpEntity res = response.getEntity();
if (res != null) {
return JsonUtils.parseObject(EntityUtils.toString(res, Charset.forName("UTF-8")), HttpClientResult.class);
}
}
} finally {
response.close();
}
} finally {
// 关闭连接,释放资源
try {
if (httpclient != null) httpclient.close();
} catch (IOException e) {}
}
return null;
}
------------------第一种上传方法结束------------------------
以下为第二种上传方法
public static final String BOUNDARY="XVUJTZYEEE";
public static final String LINE_END="\r\n";
public static final String PREFIX="--";
/**上传文件,并将上传结构转为string*/
public static String upfile(String serviceUrl,InputStream fileStream,String fileName){
HttpURLConnection conn = null;
DataOutputStream out=null;
try {
URL url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(1000000); // 连接的超时时间
conn.setReadTimeout(1000000); // 读数据的超时时间
conn.setDoOutput(true); // 必须设置此方法, 允许输出
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
out = new DataOutputStream(conn.getOutputStream());
StringBuffer strBuf = new StringBuffer();
strBuf.append(PREFIX);
strBuf.append(BOUNDARY);
strBuf.append(LINE_END);
strBuf.append("Content-Disposition: form-data; name=\"multipartFile\"; filename=\"" + fileName + "\"" + LINE_END).append(LINE_END);
out.write(strBuf.toString().getBytes());
int bytes=0;
byte[] bufferOut = new byte[10240];
while((bytes=fileStream.read(bufferOut))!=-1){
out.write(bufferOut, 0, bytes);
}
out.write(LINE_END.getBytes());
out.write((PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes());
out.flush();
int responseCode = conn.getResponseCode();
if(responseCode == 200) {
InputStream is = conn.getInputStream();
String content = getStringFromInputStream(is);
logger.error("--------------文件上传结果"+content);
return content;
}else{
logger.error("--------------文件上传返回码"+responseCode);
}
} catch (Exception e) {
logger.error("文件上传失败",e);
return null;
} finally {
if(conn != null) {
conn.disconnect();
}
if(fileStream!=null){
try {
fileStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
private static String getStringFromInputStream(InputStream is){
String result =null;
ByteArrayOutputStream baos =null;
try{
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
int len = -1;
while((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
result = baos.toString();
}catch(Exception e){
logger.error("获取结果失败",e);
}finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(baos!=null){
try {
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}