一个很好的工具类,用于将本地指定的流文件上传到服务器上。好东西就是要大家分享,只要调用它的静态方法upload()就可以实现文件的上传了,调试了可以用的!
不过要注意了:我在外网,内网测试得时候String ServerUrl = "http://219.142.157.176:8888/HealthService/upload";String ServerUrl = "http://10.205.115.586:9966/Service/upload";都是可以上传的,但是如果你的URL是这样String ServerUrl = "http://10.202.111.56:9966/Service/"的话,一定要注意后面必须的"/",不然服务器会报:302-------fail------的错误!
package cmcc.gz.platform.hbqj.utils;
import java.io.File;import java.net.FileNameMap;
import java.net.URLConnection;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
/**
*
* 类描述:上传
* 创建时间:2014-8-29 下午3:57:35
*
*/
public class UploadTest {
/*public static void main(String[] args) {
upload("E:\\工作\\Code历险记\\test.csv");
}*/
// 文件上传
public static void upload(String filepath) {
//指定服务器地址
String ServerUrl = "http://219.142.157.176:8888/HealthService/upload";PostMethod filePost = new PostMethod(ServerUrl);
try {
// StringPart:普通的文本参数,下面红色部门是给服务器传递的参数
StringPart orgId = new StringPart("orgId", "TEST");
StringPart secretKey = new StringPart("secretKey", "asdfghj");
// FilePart:用来上传文件的类
FilePart fp = new FilePart("file", new File(filepath));
fp.setContentType(getMimeType(filepath));
fp.setCharSet("utf8");
// Part:类专门用来上传文件,其子类 ,FilePart:用来上传文件的类; StringPart:普通的文本参数
Part[] parts = { orgId, secretKey, fp };
// 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
MultipartRequestEntity mre = new MultipartRequestEntity(parts, filePost.getParams());
filePost.setRequestEntity(mre);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);// 设置连接时间
int status = client.executeMethod(filePost);
if (status != HttpStatus.SC_OK) {
System.out.println(status + "--------------fail----");
} else if (status == HttpStatus.SC_OK) {
System.out.println("---------服务器返回值---------");
System.out.println(filePost.getResponseBodyAsString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getMimeType(String fileUrl) throws java.io.IOException {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String type = fileNameMap.getContentTypeFor(fileUrl);
return type;
}
}