使用restTemplate上传图片

网上有很多restTemplate上传图片的例子,但是我遇到的坑,却没有解决办法,于是在墙外面找到了解决方案,现分享如下

使用restTemplate上传图片_第1张图片

上送给微信的请求报文必须如上(事实证明少一个filename微信都提示你file不能为空)这个提示误导两个小时排查问题

代码摘要如下:

private ResultModel httpRequestWechatUploadImage(String url,String head,String body,String imageUrl,String imageName){
        try{
            //构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", head);
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            ResponseEntity responseEntity;

            //构建第一个boundary
            HttpHeaders metaHeader = new HttpHeaders();
            metaHeader.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity jsonHttpEntity = new HttpEntity<>(body, metaHeader);

            //构建第二个boundary
            HttpHeaders pictureHeader = new HttpHeaders();
            pictureHeader.setContentType(MediaType.IMAGE_JPEG);
            //不设置此contentDisposition则会报file必填
            pictureHeader.setContentDispositionFormData("file",imageName);
            ByteArrayResource bar = new ByteArrayResource(CommonUtils.getByteFromURL(imageUrl));
            HttpEntity picturePart = new HttpEntity<>(bar, pictureHeader);

            //组成body
            MultiValueMap multipartRequest = new LinkedMultiValueMap<>();
            multipartRequest.add("meta", jsonHttpEntity);
            multipartRequest.add("file", picturePart);

            //放body 和 head
            HttpEntity entity = new HttpEntity(multipartRequest, headers);
            //请求微信
            responseEntity = restTemplate().exchange(url,HttpMethod.POST,entity,String.class);
            if(responseEntity.getStatusCode() == HttpStatus.OK){
                return new ResultModel(true, responseEntity.getBody());
            }else{
                return new ResultModel(false, responseEntity.toString());
            }
        } catch(RestClientResponseException ex){
            System.out.println("rest client exception,body"+ex.getResponseBodyAsString());
            ex.printStackTrace();
            return new ResultModel(false,ex.getResponseBodyAsString());
        } catch (Exception e){
            System.out.println("exception "+e.getMessage());
            e.printStackTrace();
        }
        return new ResultModel(false,"request wechat system error");
    }

 

你可能感兴趣的:(Java,wechat,v3)