使用HttpClient上传文件资源(已验证)

来源:互联网 发布:淘宝盖楼怎么才能中 编辑:程序博客网 时间:2024/05/22 03:39

相关Jar包

Java代码

/**

* 发送请求

* @param url
*            请求地址
* @param filePath
*            文件在服务器保存路径(这里是为了自己测试方便而写,可以将该参数去掉)
* @return
* @throws IOException
*/
private String uploadSource(String url, String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return null;
}
try{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file",fileBody);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity);
System.out.println(result);
return result;
}
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}


0 0