gpt4 book ai didi

java - JSReport API 使用 Java 从响应中保存 PDF

转载 作者:行者123 更新时间:2023-12-01 18:42:20 26 4
gpt4 key购买 nike

我需要保存 POST 服务的 PDF,但总是收到错误:

“提取类型 [class java.lang.Object] 和内容类型 [application/pdf] 的响应时出错;嵌套异常为 org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:意外字符('%' (代码 37)):需要一个有效值(JSON 字符串、数字、数组、对象或标记“null”、“true”或“false”);嵌套异常是 com.fasterxml.jackson.core.JsonParseException:意外字符('%'(代码 37)):需要一个有效值(JSON 字符串、数字、数组、对象或标记 'null'、'true' 或 'false ')"

我正在使用 Spring Boot 和 RestTemplate

示例:

public static final String base_url = "https://evx.jsreportonline.net/api/report";

static {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("evx.jsreportonline.net"));
}

private HttpHeaders getHeaders() {
if (null == headers) {
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.ALL));
headers.add("Authorization", "Basic " + Base64.getEncoder().encodeToString("test_pdf:test_pdf".getBytes()));
}
return headers;
}

public void getRepo() {

List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
RestTemplate restTemplate = new RestTemplate();
Json jsonObj = new Json("{\"template\":{\"shortid\":\"JCdUaT_\"},\"data\":null}");

// REQUEST
HttpEntity<Object> entity = new HttpEntity<>(jsonObj, this.getHeaders());

/* MENSAGE CONVERTER */
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);

/* RESPONSE */
try {
Object result = restTemplate.postForObject(base_url, entity, Object.class);
byte[] resultByteArr = (byte[]) result;
} catch (Exception e) {
System.out.println(e.getMessage() + " " + e);
}
}

最佳答案

在这种情况下,curl 对于调试非常有用。

如果我使用您的属性、身份验证、json 有效负载和 api 端点,并使用curl 发布请求

curl -i --user test_pdf:test_pdf -H "内容类型:application/json"-H "接受:application/json"-X POST -d '{"template":{"shortid":"JCdUaT_"},"data":null}' https://evx.jsreportonline.net/api/report

我得到以下回复

HTTP/2 200 
date: Fri, 24 Jan 2020 19:45:07 GMT
content-type: application/pdf
server: nginx/1.17.6
x-powered-by: Express
access-control-allow-origin: *
access-control-expose-headers: *
set-cookie: render-complete=true; Path=/
set-cookie:
content-disposition: inline;filename=invoice-main.pdf
jo-credits-spent: 1.12

Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file.

这告诉我我正在获取二进制数据作为响应。在这种情况下,我需要使用不同的转换器。尝试使用“ByteArrayHttpMessageConverter”,如下所示 good ans

关于java - JSReport API 使用 Java 从响应中保存 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59902560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com