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();
    }
posted @ 2022-04-12 22:03  枫树湾河桥  阅读(745)  评论(0编辑  收藏  举报
Live2D