public static String getMimeType(String fileUrl) throws java.io.IOException {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String type = fileNameMap.getContentTypeFor(fileUrl);
return type;
}
// 上传带附件的参数:
public static String uploadFile(String filePath, String id, int bid) {
File file = new File(
"D:\\workspace\\NewsRobot\\download\\laddyphoto\\37294_236809_702347.jpg");
if (!file.exists()) {
return "文件不存在!";
}
String url = "http://www.chahushequ.com/post.bbscs";
PostMethod filePost = new PostMethod(url);
//仅设置User-Agent就行,不用设置Content-Type,设置了Content-Type有可能导致上传不成功
filePost .setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20100101 Firefox/8.0");
// set cookie
if (_cookies != null) {
filePost.setRequestHeader("Cookie", _cookies);
}
try {
// FilePart:用来上传文件的类
FilePart fp = new FilePart("headImageFile", file); // Part:类专门用来上传文件,其子类
// ,FilePart:用来上传文件的类
// StringPart:普通的文本参数
System.out.println("---" + fp);
fp.setContentType(getMimeType(filePath));
// StringPart:普通的文本参数
StringPart idPart = new StringPart("id", "");
StringPart bidPart = new StringPart("bid", String.valueOf(bid));
StringPart action = new StringPart("action", "upfiledo");
Part[] parts = { idPart, bidPart, action, fp };
// 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
MultipartRequestEntity mre = new MultipartRequestEntity(parts,
filePost.getParams());
filePost.setRequestEntity(mre);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(
50000);// 设置连接时间
int status = client.executeMethod(filePost);
System.out.println(status + "--------------");
if (status != HttpStatus.SC_OK) {
System.out.println(status + "--------------fail----");
} else if (status == HttpStatus.SC_OK) {
String str = "";
str = filePost.getResponseBodyAsString();
System.out.println(filePost.getResponseBodyAsString()
+ "---------服务器返回值---------");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}