1 Star 0 Fork 1

久约而逝 / UploadFile

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
HttpRequester.java 7.83 KB
一键复制 编辑 原始数据 按行查看 历史
package com.mei.uploadfile.http;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2015/8/4.
*/
public class HttpRequester {
/**
* 直接通过http协议提交数据到服务器,事变如下表单的提交功能
* <form method="post" action="http://192.168.1.102:8080/ssi/fileload/test.do" enctype="multipart/form-data">
* <input type="text" name="name">
* <input type="text" name="id">
* <input type="file" name="imagefile"/>
* <input type="file" name="zip"/>
* <input type="button" value="submit"/>
* </form>
* @param actionUrl 上传路径
* @param params 请求参数 key为参数名,value为参数值
* @param files 上传的文件
* @return
*/
public static String post(String actionUrl,Map<String,String> params,FormFile[] files){
try{
String BOUNDARY="--------777777777777777";//数据分隔线
String MULTIPART_FORM_DATA="multipart/form-data";
URL url=new URL(actionUrl);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setDoInput(true);//允许输入
conn.setDoOutput(true);//允许输出
conn.setUseCaches(false);//不使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);
StringBuilder sb=new StringBuilder();
for (Map.Entry<String,String> entry:params.entrySet()){
//构建表单字段内容
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition:form-data; name=\""+entry.getKey()+"\"\r\n\r\n");
sb.append(entry.getValue());
sb.append("\r\n");
}
DataOutputStream outStream=new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());//发送表单字段数据
for (FormFile file:files){
//发送文件数据
StringBuilder split=new StringBuilder();
split.append("--");
split.append(BOUNDARY);
split.append("\r\n");
split.append("Content-Disposition:form-data;name=\""+file.getFormname()
+"\";filename=\""+file.getFilename()+"\"\r\n");
split.append("Content-Type:" + file.getContentType() + "\r\n\r\n");
outStream.write(split.toString().getBytes());
if (file.getInStream()!=null){
byte[] buffer=new byte[1024];
int len=0;
while ((len=file.getInStream().read(buffer))!=-1){
outStream.write(buffer,0,len);
}
file.getInStream().close();
}else {
outStream.write(file.getData(),0,file.getData().length);
}
outStream.write("\r\n".getBytes());
}
byte[] end_data=("--"+BOUNDARY+"--\r\n").getBytes();//数据结束标志
outStream.write(end_data);
outStream.flush();
int cah=conn.getResponseCode();
if (cah!=200){
throw new RuntimeException("请求URL失败");
}
InputStream is=conn.getInputStream();
int ch;
StringBuilder b=new StringBuilder();
while ((ch=is.read())!=-1){
b.append((char)ch);
}
outStream.close();
conn.disconnect();//断开连接
return b.toString();
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 提交数据到服务器
* @param actionUrl 上传路径
* @param params 请求参数key为参数名,value为参数值
* @param file 上传文件
* @return
*/
public static String post(String actionUrl,Map<String,String> params,FormFile file){
return post(actionUrl,params,new FormFile[]{file});
}
public static byte[] postFormHttpClient(String path,Map<String,String> params,String encode) throws Exception{
List<NameValuePair> formparams=new ArrayList<>();//用于存放请求参数
for (Map.Entry<String,String> entry:params.entrySet()){
formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,"UTF-8");
HttpPost httpPost=new HttpPost(path);
httpPost.setEntity(entity);
HttpClient httpClient=new DefaultHttpClient();//看做是浏览器
HttpResponse response=httpClient.execute(httpPost);//发送post请求
return StreamTool.readInputSream(response.getEntity().getContent());
}
/**
* 发送请求
* @param path 请求路径名
* @param params 请求参数 key为参数名称 value为参数值
* @param encode 请求参数的编码
* @return
* @throws Exception
*/
public static byte[] post(String path,Map<String,String> params,String encode) throws Exception{
//String params="method=save&name="+URLEncoder.encode("老毕","UTF-8")+"&age=28&";//需要发送的参数
StringBuilder parambuilder=new StringBuilder("");
if (params!=null&&!params.isEmpty()){
for (Map.Entry<String,String> entry:params.entrySet()){
parambuilder.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(),encode))
.append("&");
}
parambuilder.deleteCharAt(parambuilder.length()-1);
byte[] data=parambuilder.toString().getBytes();
URL url=new URL(path);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);//允许对外发送请求数据
conn.setUseCaches(false);//不进行缓存
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("POST");
//下面设置http请求头
conn.setRequestProperty("Accept","image/gif,image/jpeg,image/pjpeg," +
"image/pjpeg,application/x-shockwave-flash,application/xaml+xml," +
"application/vnd.ms-xpsdocument,application/x-ms-xbap," +
"application/x-ms-application,application/vnd.ms-excel," +
"application/vnd.ms-powerpoint,application/msword,*/*");
conn.setRequestProperty("Accept-Agent","Mozilla/4.0(compatible;MSIE 8.0;Windows NT 5.2;Trident/4.0; .NET CLR 1.1.4322;" +
".NET CLR 2.0.50727; .NET CLR 3.0.04506.30; NET CLR 3.0.4506.2152; .NET CLR 3.5.30729");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",String.valueOf(data.length));
conn.setRequestProperty("Connection","Keep-Alive");
//发送参数
DataOutputStream outputStream=new DataOutputStream(conn.getOutputStream());
outputStream.write(data);//把参数发送出去
outputStream.flush();
outputStream.close();
if (conn.getResponseCode()==200){
return StreamTool.readInputStream(conn.getInputStream());
}
return null;
}
}
}
Android
1
https://gitee.com/meiSThub/UploadFile.git
git@gitee.com:meiSThub/UploadFile.git
meiSThub
UploadFile
UploadFile
master

搜索帮助