OkHttp 通过post请求上传文件

一、添加pom 依赖



    com.squareup.okhttp3
    okhttp
    3.10.0

二、上产文件接口编写
@ApiOperation("上传文件(移动云)")
@PostMapping("/uploadFileToOos")
public ResultJson uploadFileToOos(@RequestParam("file") MultipartFile file) throws IOException {
    String fileName = file.getOriginalFilename();
    File sendFile = new File("/tmp/tmp-" + fileName + "");
    try {
        file.transferTo(sendFile);
        OkHttpClient httpClient = new OkHttpClient();
        MediaType mediaType = okhttp3.MediaType.parse(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE);

        String policy = "{ \"expiration\": \"" + OosCommonUtil.getExpireTime() + "\",\n" +
                "  \"conditions\": [\n" +
                "    {\"bucket\": \"" + haimen_bucket + "\" },\n" +
                "{\"key\":\"" + fileName + "\"}" +
                "  ]\n" +
                "}";

        RequestBody fileBody = RequestBody.create(mediaType, sendFile);
        String base64Policy = OosCommonUtil.getBase64Policy(policy);

        String signature = OosCommonUtil.signWithHmacSha1(secretAccessKey, base64Policy);

        RequestBody requestBody = new MultipartBody.Builder().
                setType(MultipartBody.FORM)
                .addFormDataPart("key", fileName)
                .addFormDataPart("AccessKeyId", accessKeyId)
                .addFormDataPart("policy", base64Policy)
                .addFormDataPart("signature", signature)
                .addFormDataPart("file", fileName, fileBody).build();

        Request request = new Request.Builder()
                .post(requestBody)
                .url(obsUri)
                .addHeader("Date", OosCommonUtil.getObsHeaderDate(System.currentTimeMillis()))
                .addHeader("Host", host)
                .addHeader("Content-Type", org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE)
                .addHeader("Origin", origin)
                .build();

        Response response = httpClient.newCall(request).execute();
        if (response != null) {
            if (response.code() == 204) {
                AliOssResponse aliOssResponse = new AliOssResponse();
                aliOssResponse.setSize(file.getSize());
                aliOssResponse.setUrl(obsUri + "/" + fileName);
                return ResultJson.getInstance().setData(aliOssResponse).setCode(200).setMsg("success");
            } else {
                return ResultJson.getInstance().setData(null).setCode(200).setMsg("error");
            }
        }
        return ResultJson.getInstance().setData(null).setCode(200).setMsg("error");
    } finally {
        if (sendFile.exists()) {
            sendFile.delete();
        }
    }
}

 

你可能感兴趣的:(java,okhttp)