• Java发送Post请求上传图片


    原文链接: https://www.cnblogs.com/enjoybeng/p/15403387.html

    最近公司需要对接一个第三方平台,以前的接口POST请求只是发送key,value字符串,这次接口提供的字段中除了有String类型,还包含了File类型,找到两种方式来解决:
    主方法

     
    public static void main(String[] args) throws IOException {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String format = df.format(new Date());// new Date()为获取当前系统时间
            String filePath1 = "C:\\Users\\Administrator\\Desktop\\2021101117.png";
            String filePath2 = "C:\\Users\\Administrator\\Desktop\\2021101118.png";
            File file1=new File(filePath1);
            File file2=new File(filePath2);
            File[] files = new File[2];
            files[0] = file1;
            files[1] = file2;
            String url = "XXXXX" ;
            String appsecret = "XXXX";
            HashMap<String,String> params = new HashMap<String,String>();
            params.put("appkey", "XXXXX");
            String appkey="XXXXX";
            params.put("method", "fileUpload");
            String method="fileUpload";
            params.put("timestamp",format);
            String  timestamp=format;
            params.put("customerId","XXX");
            String  customerId="XXX";
            params.put("businessTypeKey","XXX");
            String  businessTypeKey="XXX";
            String sign = SignUtils.getSign(appsecret,params);
            params.put("sign",sign);
            String url_final=url+"?appkey="+appkey+"&method="+method+"&timestamp="+timestamp+"&customerId="+customerId+"&businessTypeKey="+businessTypeKey+"&sign="+sign;
            Map<String,Object> results = postAction(url_final,files);   //第一种方式:unirest
            String results = sendPost(String strurl,String fileName); //第二种方式:okhttp
            System.out.println(results.toString());
        }
    

    第一种方式:unirest

     
    /**第一种方式
         <dependency>
         <groupId>com.konghq</groupId>
         <artifactId>unirest-java</artifactId>
         <version>3.11.11</version>
         </dependency>
         * @param url
         * @param files
         * @return
         */
        public static Map<String,Object>  postAction(String url,File[] files) {
            Map<String,Object> resultMap=new HashMap<>();
            try {
                kong.unirest.HttpResponse<String> response = Unirest.post(url)
                        .header("accept", "*/*")
                        .field("files", files[0])
                        .field("files", files[1])
                        .asString();
                String	content= response.getBody().toString();
                String	statusText= response.getStatusText();
                String	status= String.valueOf(response.getStatus());
                resultMap.put("content", content);
                resultMap.put("statusText", statusText);
                resultMap.put("status", status);
                if(!status.equals("200")) {
                    SUCCESS=false;
                }
                resultMap.put("isSuc", SUCCESS);
            }catch (Exception e) {
                SUCCESS=false;
                resultMap.put("isSuc", SUCCESS);
            }
            return resultMap;
        }
    

    第二种方式:okhttp

     
    /**第二种方式
         * <dependency>
         <groupId>com.squareup.okhttp3</groupId>
         <artifactId>okhttp</artifactId>
         <version>3.2.0</version>
         </dependency>
         * @param strurl
         * @param files
         * @throws IOException
         */
        public static String sendPost(String strurl,File[] files) throws IOException {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("multipart/form-data");
    
            MultipartBody.Builder builder1 = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (int i = 0 ; i < files.length; i++){
                builder1.addFormDataPart("files",files[i].getName(),RequestBody.create(MediaType.parse("application/octet-stream"), files[i]));
            }
            RequestBody body = builder1.build();
    
            Request request = new Request.Builder()
                    .url(strurl)
                    .method("POST", body)
                    .addHeader("accept", "*/*")
                    .addHeader("Content-Type", "multipart/form-data")
                    .build();
            Response response = client.newCall(request).execute();
            InputStream inputStream = response.body().byteStream();
            byte[] getData = readInputStream(inputStream);
            inputStream.read(getData);
            String str = new String(getData);
            System.out.println (str);
            return str;
        }
    
        public static  byte[] readInputStream(InputStream inputStream) throws IOException {
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            return bos.toByteArray();
        }
  • 相关阅读:
    loj #6201. 「YNOI2016」掉进兔子洞
    poj 3683 Priest John's Busiest Day
    hdu 1814 Peaceful Commission
    poj 3207 Ikki's Story IV
    loj #2305. 「NOI2017」游戏
    uoj #111. 【APIO2015】Jakarta Skyscrapers
    洛谷P1550 [USACO08OCT]打井Watering Hole
    uoj #110. 【APIO2015】Bali Sculptures
    loj #2116. 「HNOI2015」开店
    codevs 3044 矩形面积求并
  • 原文地址:https://www.cnblogs.com/fswhq/p/16135593.html
Copyright © 2020-2023  润新知