欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

利用 HttpClient 上传文件,,最近的工作需要把从网络上

来源: javaer 分享于  点击 24139 次 点评:219

利用 HttpClient 上传文件,,最近的工作需要把从网络上


最近的工作需要把从网络上抓取的图片批量上传到服务器,文件上传用的是ApacheHttpClient4.3,记录一下以便以后查阅! 代码如下:

    /**      * Example how to use multipart/form encoded POST request.      */      public class ClientMultipartFormPost {          public static void main(String[] args) throws Exception {              if (args.length != 1)  {                  System.out.println("File path not given");                  System.exit(1);              }              CloseableHttpClient httpclient = HttpClients.createDefault();              try {                  HttpPost httppost = new HttpPost("http://localhost:8080" +                          "/servlets-examples/servlet/RequestInfoExample");                  FileBody img = new FileBody(new File(args[0]));                  StringBody filename = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);                  StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);                  HttpEntity reqEntity = MultipartEntityBuilder.create()                          .addPart("img", img)                          .addPart("filename", filename)                          .addPart("comment", comment)                          .build();                  httppost.setEntity(reqEntity);                  System.out.println("executing request " + httppost.getRequestLine());                  CloseableHttpResponse response = httpclient.execute(httppost);                  try {                      System.out.println("----------------------------------------");                      System.out.println(response.getStatusLine());                      HttpEntity resEntity = response.getEntity();                      if (resEntity != null) {                          System.out.println("Response content length: " + resEntity.getContentLength());                      }                      EntityUtils.consume(resEntity);                  } finally {                      response.close();                  }              } finally {                  httpclient.close();              }          }      }  

HttpClient的更多用法可参考官方文档:https://hc.apache.org/httpcomponents-client-4.3.x/examples.html

相关栏目:

用户点评