【问题标题】:Get value of an object from Response entity从响应实体中获取对象的值
【发布时间】:2019-08-08 11:20:00
【问题描述】:

您好,我想从响应字符串中获取 fileContent 的值

我的控制器

@RestController
@Component
@RequestMapping("/rest")
public class SigningControllerREst {
 @PostMapping("/uploadFile50")
        public ResponseEntity<?> uploadFile50(@RequestParam("file") MultipartFile file) 
                throws FileNotFoundException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, RubricaException  {
           ...
        UploadFileResponse up=new UploadFileResponse(fileName, fileDownloadUri,
                    file.getContentType(), file.getSize(),result);
            return new ResponseEntity<UploadFileResponse>(up, HttpStatus.OK);
        }

客户

File inFile = new File("C:\\Users\\admin-pc\\Desktop\\CV.pdf");
FileInputStream fis = null;
try {
    fis = new FileInputStream(inFile);
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

    // server back-end URL
    HttpPost httppost = new HttpPost("http://localhost:8094/rubi/rest/uploadFile");
    MultipartEntity entity = new MultipartEntity();

    // set the file input stream and file name as arguments
    entity.addPart("file", new InputStreamBody(fis, inFile.getName()));
    httppost.setEntity(entity);
    // execute the request
    HttpResponse response = httpclient.execute(httppost);
    int statusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");

    System.out.println(responseString );

} catch (ClientProtocolException e) {
    System.err.println("Unable to make connection");
    e.printStackTrace();
} catch (IOException e) {
    System.err.println("Unable to read file");
    e.printStackTrace();
} finally {
    try {
        if (fis != null) fis.close();
    } catch (IOException e) {}
}

输出

{"fileName":"CV.pdf","fileDownloadUri":"http://localhost:8094/rubi/downloadFile/CV.pdf","fileType":"application/octet-stream","fileContent":"Content in bytes","size":363629}

我想要的是 responseStringfileContent 的值(太长),我怎样才能得到那个值。

感谢您的帮助。

【问题讨论】:

    标签: java spring rest spring-boot http-post


    【解决方案1】:

    你可以这样得到它:

    Map<String, Object> responseMap = new com.fasterxml.jackson.databind.ObjectMapper().readValue(fileContent, Map.class);
    
    String fileContent = responseMap.get("fileContent").toString();
    

    【讨论】:

      【解决方案2】:

      只需将返回对象从UploadFileResponse改为byte[]即可解决 从

      更改此行
      return new ResponseEntity<UploadFileResponse>(up, HttpStatus.OK);
      

       return new ResponseEntity<byte[]>(result, HttpStatus.OK);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-16
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        • 2019-07-08
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多