m0_47799925 2023-03-15 13:34 采纳率: 14.3%
浏览 10
已结题

使用httpclient向另一个接口发送请求遇到的问题

我开启了两个springboot的服务。 两个的ip都是本机,一个端口是8080,另外一个是8082。

我使用8080端口的upload 接口 向 8082 端口的 receive 接口发送httpclient请求。

但是返回的response 返回的code是500,好心人们能帮我看看吗?‘

upload代码如下

@PostMapping("/upload")
    public Result<Void> upload(@RequestParam(value = "file") MultipartFile file,  //这样接收文件
                         @RequestParam(required = false) Map<String,Object> params,
                         HttpServletRequest request){

        Result result = new Result();

        File file2 = null;
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        List<Map<String,Object>> data = new ArrayList<>();
        try {
            file2 = File.createTempFile(fileName, prefix);
            // 将上传文件复制到临时文件
            //Springboot中直接用transferTo会报找不到路径的错,得复制一份才行
            FileUtils.copyInputStreamToFile(file.getInputStream(),file2);
            HashMap param = new HashMap();
            //调用远程发送接口
            String content=getRemoteInterfaceStr("receive",param,file2);
            // 返回前台
            result.setData(content);
            result.setState(200);
            result.setMessage("上传成功");
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            throw new FileUploadFailedException("上传文件失败");
        }
    }



    public String getRemoteInterfaceStr(String actionName,HashMap params,File file1) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://localhost:8082/receive");
        CloseableHttpResponse response = null;
        try {
            // 将上传文件复制到临时文件
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            ContentType strContent = ContentType.create("text/plain", Charset.forName("UTF-8"));
            builder.addTextBody("attachmentType","certificate" , strContent);
            FileBody bin = new FileBody(file1);
            builder.addPart("file", bin);
            //传文字参数
            // builder.addPart("attachmentType",
            //         new StringBody("certificate", ContentType.create("text/plain", Consts.UTF_8)));
            HttpEntity parameterEntity = builder.build();
            //这里不要自己制定header,它会自己模拟,你自己指定了就会报错
            //post.setHeader("Content-type", "multipart/form-data");
            post.setEntity(parameterEntity);
            response = httpClient.execute(post, HttpClientContext.create());
            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity());
                return content;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(response !=null){
                response.close();
            }
        }
        return null;
    }
receive代码如下
@PostMapping("/receive")
    public Result<String> receive(HttpSession session, @RequestParam("file") MultipartFile file){


        // 判断上传的文件是否为空
        if (file.isEmpty()) {
            // 是:抛出异常
            throw new FileEmptyException("上传的文件不允许为空");
        }

        //保存文件
        //获取当前项目的绝对路径
//        String parent = session.getServletContext().getRealPath("upload");
        String parent = "E:\\123\\upload";
        File dir = new File(parent);
        if(!dir.exists()){
            dir.mkdir();
        }
        //获取当前文件的后缀名
        String originalFilename = file.getOriginalFilename();
        int beginIndex = originalFilename.lastIndexOf(".");
        String suffix = "";
        //后缀
        if(beginIndex>0){
            suffix = originalFilename.substring(beginIndex);
        }
        //使用uuid 随机前缀文件名
        String prefix = UUID.randomUUID().toString();
        //全图片名
        String filename = prefix + suffix;

        //创建文件对象,表示保存文件的头像文件
        File dest = new File(dir,filename);

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new FileUploadIOException("上传文件读写错误,请重试");
        } catch (IllegalStateException e){
            throw new FileStateException("文件状态异常");
        }

        //将文件路径上传到数据库
//        String avatar = "/file/" + filename;
//        Integer uid = getUidFromSession(session);
//        crossDomainService.uploadAvatarInMysql(uid,avatar);
        return new Result<String>(SUCCESS);//,avatar
    }

  • 写回答

2条回答 默认 最新

  • threenewbee 2023-03-15 13:38
    关注

    500,是对方的服务器出现内部错误,检查下提交的数据是否合法,如果合法就是对方服务器代码问题了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月23日
  • 已采纳回答 3月15日
  • 创建了问题 3月15日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改