![](/img/trans.png)
[英]How to document swagger specification which returns ResponseEntity<Resource> where Resource is org.springframework.core.io.Resource
[英]How to handle org.springframework.core.io.Resource for Swagger Codegen
我正在使用Spring Boot 2開發一個Web應用程序,它有兩個Spring項目協同工作:一個是通過REST API為應用程序邏輯提供服務的REST API服務器,另一個是負責呈現網頁和調用API服務器的Web項目。 Web項目使用Swagger Codegen自動生成用於調用API的類。
在API服務器中,我有一個控制器ResourceController
,其端點用於提供文件內容(即下載文件),如下所示
@GetMapping("/files/{uuid}")
@ResponseBody
public org.springframework.core.io.Resource getFile(@PathVariable String uuid) {
String systemPath = fileService.getFilePath(uuid);
return new FileSystemResource(systemPath);
}
在Web客戶端,Swagger使用轉換為的方法生成ResourceControllerApi
public io.swagger.client.model.Resource getFileUsingGET(String uuid) {...}
我想在Web項目中創建一個控制器,該控制器通過用戶瀏覽器和API服務器之間的請求和響應。 我試過了
@GetMapping("/client/files/{uuid}")
@ResponseBody
public io.swagger.client.model.Resource getFile(@PathVariable String uuid) {
return resourceControllerApi.getFileUsingGET(uuid);
}
在調用API時(在客戶端Web上),我收到此錯誤
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class io.swagger.client.model.Resource] and content type [image/jpeg]
我希望當我把網址如http://myweb/client/files/dee38be4-6ef9-460d-bc44-f1b93770ab83
,瀏覽器下載文件內容。 我一直在尋找一種方法將io.swagger.client.model.Resource
轉換為org.springframework.core.io.Resource
但無法弄清楚。
以下是自動生成的io.swagger.client.model.Resource
的內容
/*
* NPA Marketplace REST API
* API to manage NPA Marketplace.
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.client.model.InputStream;
import io.swagger.client.model.URI;
import io.swagger.client.model.URL;
/**
* Resource
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-03-08T14:55:08.754+07:00")
public class Resource {
@JsonProperty("description")
private String description = null;
@JsonProperty("file")
private java.io.File file = null;
@JsonProperty("filename")
private String filename = null;
@JsonProperty("inputStream")
private InputStream inputStream = null;
@JsonProperty("open")
private Boolean open = null;
@JsonProperty("readable")
private Boolean readable = null;
@JsonProperty("uri")
private URI uri = null;
@JsonProperty("url")
private URL url = null;
public Resource description(String description) {
this.description = description;
return this;
}
/**
* Get description
* @return description
**/
@ApiModelProperty(value = "")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Resource file(java.io.File file) {
this.file = file;
return this;
}
/**
* Get file
* @return file
**/
@ApiModelProperty(value = "")
public java.io.File getFile() {
return file;
}
public void setFile(java.io.File file) {
this.file = file;
}
public Resource filename(String filename) {
this.filename = filename;
return this;
}
/**
* Get filename
* @return filename
**/
@ApiModelProperty(value = "")
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Resource inputStream(InputStream inputStream) {
this.inputStream = inputStream;
return this;
}
/**
* Get inputStream
* @return inputStream
**/
@ApiModelProperty(value = "")
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public Resource open(Boolean open) {
this.open = open;
return this;
}
/**
* Get open
* @return open
**/
@ApiModelProperty(value = "")
public Boolean isOpen() {
return open;
}
public void setOpen(Boolean open) {
this.open = open;
}
public Resource readable(Boolean readable) {
this.readable = readable;
return this;
}
/**
* Get readable
* @return readable
**/
@ApiModelProperty(value = "")
public Boolean isReadable() {
return readable;
}
public void setReadable(Boolean readable) {
this.readable = readable;
}
public Resource uri(URI uri) {
this.uri = uri;
return this;
}
/**
* Get uri
* @return uri
**/
@ApiModelProperty(value = "")
public URI getUri() {
return uri;
}
public void setUri(URI uri) {
this.uri = uri;
}
public Resource url(URL url) {
this.url = url;
return this;
}
/**
* Get url
* @return url
**/
@ApiModelProperty(value = "")
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Resource resource = (Resource) o;
return Objects.equals(this.description, resource.description) &&
Objects.equals(this.file, resource.file) &&
Objects.equals(this.filename, resource.filename) &&
Objects.equals(this.inputStream, resource.inputStream) &&
Objects.equals(this.open, resource.open) &&
Objects.equals(this.readable, resource.readable) &&
Objects.equals(this.uri, resource.uri) &&
Objects.equals(this.url, resource.url);
}
@Override
public int hashCode() {
return Objects.hash(description, file, filename, inputStream, open, readable, uri, url);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Resource {\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" file: ").append(toIndentedString(file)).append("\n");
sb.append(" filename: ").append(toIndentedString(filename)).append("\n");
sb.append(" inputStream: ").append(toIndentedString(inputStream)).append("\n");
sb.append(" open: ").append(toIndentedString(open)).append("\n");
sb.append(" readable: ").append(toIndentedString(readable)).append("\n");
sb.append(" uri: ").append(toIndentedString(uri)).append("\n");
sb.append(" url: ").append(toIndentedString(url)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
錯誤
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class io.swagger.client.model.Resource] and content type [image/jpeg]
是從線上發出的
ResponseEntity<T> responseEntity = restTemplate.exchange(requestEntity, returnType);
在類io.swagger.client.ApiClient
,它由變量庫resttemplate
的Swagger Codegen自動生成,即相當於運行命令java -jar swagger-codegen-cli.jar generate -i api-specs.json -l java --library resttemplate
該錯誤表明resttemplate不知道如何將響應數據轉換為io.swagger.client.model.Resource
並提示我們創建合適的HttpMessageConverter
。 這是一個用於創建HttpMessageConverters並使用resttemplate注冊它們的教程 。
但是,在我的情況下, HttpMessageConverter
不能成為解決方案,因為生成的io.swagger.client.model.Resource
沒有屬性來保存API響應中的文件數據。 似乎Swagger Codegen誤解了API服務器上的控制器將返回org.springframework.core.io.Resource
的JSON表示,從而生成計數器部分io.swagger.client.model.Resource
用於在客戶端接收JSON數據,但API服務器實際上使用文件數據流而不是JSON進行響應。
我不知道這是否可能是Swagger Codegen的錯誤,或者我做錯了一些如何。
不過,我決定放棄在API服務器上使用org.springframework.core.io.Resource
。 相反,我將控制器的返回類型更改為ResponseEntity<byte[]>
並手動配置響應頭以具有正確的內容類型和文件名,如下所示
ResourceController(API服務器)
@GetMapping("/files/{uuid}")
@ResponseBody
public ResponseEntity<byte[]> getFile(@PathVariable String uuid) {
FileMetadata myFileData = fileService.getFileMetadata(uuid);
org.springframework.core.io.Resource res = new FileSystemResource(myFileData.getPaht());
byte[] data = IOUtils.toByteArray(res.getInputStream());
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentType(MediaType.valueOf(myFileData.getContentType()));
respHeaders.setContentLength(res.getFile().length());
respHeaders.setContentDispositionFormData("attachment", myFileData.getName());
return new ResponseEntity<>(data ,respHeaders, HttpStatus.OK);
}
在Web客戶端,然后我將從API服務器接收的byte[]
數據轉換為org.springframework.core.io.Resource
,並從API服務器傳遞響應頭。
Web客戶端服務器上的控制器
@GetMapping("/client/files/{uuid}")
@ResponseBody
public ResponseEntity<org.springframework.core.io.Resource> getFile(@PathVariable String uuid) {
byte[] data = resourceControllerApi.getFileUsingGET(uuid);
HttpHeaders responseHeader = (HttpHeaders) RequestContextHolder.getRequestAttributes().getAttribute("responseHeader", RequestAttributes.SCOPE_REQUEST);
return new ResponseEntity<>(new ByteArrayResource(data), responseHeader, HttpStatus.OK);
}
關於我用來檢索響應頭的方式,因為我無法從生成的api類中獲取響應頭,所以我必須創建一個ClientHttpRequestInterceptor
來獲取頭並將其作為請求屬性。
public class ResponseHeaderClientRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
HttpHeaders responseHeader = response.getHeaders();
RequestAttributes requestAttrs = RequestContextHolder.getRequestAttributes();
if (requestAttrs != null) {
requestAttrs.setAttribute("responseHeader", responseHeader, RequestAttributes.SCOPE_REQUEST);
}
return response;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.