首页 > 技术文章 > 上传文件

anni-qianqian 2016-03-04 21:40 原文

HttpClient client = new DefaultHttpClient();
//http://localhost:8080/FileUpload/FileUploadServlet
String path = "http://localhost:8080/FileUpload/FileUploadServlet";
HttpPost post = new HttpPost(path);
//由于这里要上传文件。所以需要改变form的enctype属性。改为mul/data-form
MultipartEntity entity = new MultipartEntity();
//封装文件。
FileBody body = new FileBody(new File("f:\\qianfeng.png"));
FormBodyPart pary = new FormBodyPart("form1", body);
//将封装文件的对象添加到MultipartEntity对象里。
entity.addPart(pary);
//添加其他的数据。
entity.addPart("username", new StringBody("admin"));
entity.addPart("password", new StringBody("123"));

//设置给HttpPost对象。
post.setEntity(entity);
//执行请求。
HttpResponse response = client.execute(post);
//得到响应码。
int code = response.getStatusLine().getStatusCode();
if(code==200){
    HttpEntity result_entity = response.getEntity();
    String str = EntityUtils.toString(result_entity);
    System.out.println(str);
}

 

推荐阅读