java调用第三方接口上传文件

java调用第三方接口上传文件

不多说,直接上代码‘
pom.xml文件:

        
            org.apache.httpcomponents
            httpclient
            4.5.2
        
        
            org.apache.httpcomponents
            httpmime
            4.5.2
        

接口:

    @ApiOperation(notes = "材料上传", value = "材料上传")
    @PostMapping(value = "uploadMaterial")
    public RS uploadImage(@RequestParam(value = "upload")@ApiParam("要上传的文件") MultipartFile upload, @ApiParam("其他参数")String params) {
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        //服务端要调用的外部接口
        String url ="这里填写调用接口的路径";
        //httpclients构造post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            String originFileName = null;
            originFileName = upload.getOriginalFilename();
            // 设置上传文件流(需要是输出流),设置contentType的类型
            builder.addBinaryBody("upload", upload.getBytes(), ContentType.MULTIPART_FORM_DATA, originFileName);
            //post请求中的其他参数
            builder.addTextBody("param",param);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            HttpResponse response = httpClient.execute(httpPost);
            //接收调用外部接口返回的内容
            HttpEntity responseEntity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200){
                //响应内容都存在content中
                InputStream content = responseEntity.getContent();
                in = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
                JSONObject jsonObject = JSONObject.parseObject(result.toString());
                return new RS<>(jsonObject.get("data"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {//处理结束后关闭httpclient的链接
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return RS.serverInternalError("操作失败");
    }

亲测,没问题!(RS是楼主自己公司定义的返回结果对象,需要用的本文代码的要改成自己公司的)

你可能感兴趣的:(java调用第三方接口上传文件)