您的位置:首页 > 理论基础 > 计算机网络

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

2015-08-28 11:03 381 查看
相关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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: