• 7.20Java之封装multipart/formdata格式的表单并请求API


    7.20Java之封装multipart/form-data格式的表单并请求API

    使用到的类

    • org.apache.http.entity.mime.MultipartEntityBuilder

    • ContentType

    ContentType类

    特点:

    • 提供了对应到所有的ContentType类型的参数属性

    //先根据接口的ContentType找到对应的属性--->multipart/form-data类型的属性对应的值是MULTIPART_FORM_DATA
    ContentType contentType=ContentType.MULTIPART_FORM_DATA;

    MultipartEntityBuilder类

    MultipartEntityBuilder multipartEntityBuilder = new StringBody();//传入key,value
    //StringBody类的构造器实现了传入的内容自动转为字符
    //使用MultipartEntityBuilder类下的addPart方法,该方法实现了将传入的内容填入FormBodyPart内
    //FormBodyPart类自动的构造了表单的格式
    multipartEntityBuilder.addPart();//该方法传入key-value,value的类型可以是StringBody对象

    //最后使用HttpEntity类将multipartEntityBuilder构建
    HttpEntity reqEntity = multipartEntityBuilder.build();

    整体实现代码

    package AmazonListingAPI;

    import org.apache.http.Consts;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.CookieStore;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.impl.client.BasicCookieStore;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.impl.cookie.BasicClientCookie;
    import org.apache.http.util.EntityUtils;

    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.nio.charset.Charset;

    /**
    * 测试Amazon上传图片的API
    * @since JDK 1.8
    * @date 2021/08/14
    * @author Lucifer
    */
    public class UploadFileAPITestNo2 {
       //设置文件路径
       private static File filePath = new File("C:\\Users\\Administrator\\Desktop\\Test_Work\\Test_Picture\\King.jpg");
       public static void uploadFile(String url, String cookValue){
           //设置Cookie
           CookieStore cookieStore = new BasicCookieStore();
           BasicClientCookie cookie = new BasicClientCookie("Cookie", cookValue);
           try {
               cookie.setDomain(new URL(url).getHost());
          } catch (MalformedURLException e) {
               e.printStackTrace();
          }
           cookie.setPath("/");
           cookieStore.addCookie(cookie);
           CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

           String result = "";
           //每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
           String boundary ="----WebKitFormBoundary5ZMULAAn6mngkXzn";
           try {
               //文件名
               String fileName = filePath.getName();
               HttpPost httpPost = new HttpPost(url);
               //设置请求头
               httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);

               //HttpEntity builder
               MultipartEntityBuilder builder = MultipartEntityBuilder.create();
               //字符编码
               builder.setCharset(Charset.forName("UTF-8"));
               //模拟浏览器
               builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
               //boundary
               builder.setBoundary(boundary);
               //multipart/form-data
               builder.addPart("multipartFile",new FileBody(filePath));
               // binary
    //           builder.addBinaryBody("name=\"multipartFile\"; filename=\"test.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
    //           //其他参数
    //           builder.addTextBody("filename", fileName, ContentType.create("text/plain", Consts.UTF_8));
               //HttpEntity
               HttpEntity entity = builder.build();
               httpPost.setEntity(entity);
               // 执行提交
               HttpResponse response = httpClient.execute(httpPost);
               //响应
               HttpEntity responseEntity = response.getEntity();
               if (responseEntity != null) {
                   // 将响应内容转换为字符串
                   result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
              }
          } catch (IOException e) {
               e.printStackTrace();
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               try {
                   httpClient.close();
              } catch (IOException e) {
                   e.printStackTrace();
              }
          }
           System.err.println("result"+result);
    //       return result;
      }
    }
    It's a lonely road!!!
  • 相关阅读:
    一步一步教你在GridView中实现可收缩的面板
    收藏微软面试智力题 (附答案)
    WF4.0实战(一):文件审批流程
    WF4.0实战(六):控制WPF动画
    WF4.0实战(十一):邮件通知
    WF4.0实战(十):分布式酒店订房系统
    WF4.0实战(十六):模拟红绿灯
    WF4.0实战(五):实现一个直观易扩展的自动测试框架
    Beginning WF4读书笔记(一):创建一个简单的工作流
    DataGridView打印类
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/15042544.html
Copyright © 2020-2023  润新知