java - 在 java/spring boot 中的 HTTP GET 请求中发送 JSON 正文
问题描述
我需要在 java/spring boot 中发送一个带有 json 正文的 GET 请求。我知道反对它的建议,但是我必须这样做有几个原因: 1. 我使用的第 3 方 API 只允许 GET 请求,所以 POST 不是一个选项。2. 我需要在正文中传递一个非常大的参数(大约 8-10k 个字符的逗号分隔列表),因此将查询参数附加到 url 上也不是一个选项。
我尝试了一些不同的东西:
apache HttpClient from here: Send content body with HTTP GET Request in Java。这直接从 API 本身给出了一些关于错误密钥的错误。
URIComponentsBuilder 从这里:Spring RestTemplate GET with parameters。这只是将参数添加到 url 上,正如我之前解释的那样,这不是一个选项。
restTemplate.exchange。这似乎是最简单的,但对象不会通过:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#exchange-java。 lang.String-org.springframework.http.HttpMethod-org.springframework.http.HttpEntity-java.lang.Class-java.util.Map-
以及我可能忘记的另一两件事。
这就是我在 Postman 中所说的内容。我需要能够传递这里给出的两个参数。如果通过 Postman 运行它可以正常工作,但我无法在 Java/Spring Boot 中弄清楚。
这是来自 restTemplate.exchange 尝试的代码片段:
public String makeMMSICall(String uri, List<String> MMSIBatchList, HashMap<String, String> headersList) {
ResponseEntity<String> result = null;
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
for (String key : headersList.keySet()) {
headers.add(key, headersList.get(key));
}
Map<String, String> params = new HashMap<String, String>();
params.put("mmsi", String.join(",", MMSIBatchList));
params.put("limit", mmsiBatchSize);
HttpEntity<?> entity = new HttpEntity<>(headers);
result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class, params);
System.out.println(result.getBody());
} catch (RestClientException e) {
LOGGER.error("Exception in makeGetHTTPCall :" + e.getMessage());
throw e;
} catch (Exception e) {
LOGGER.error("Exception in makeGetHTTPCall :" + e.getMessage());
throw e;
}
return result.getBody();
}
感谢您的帮助!
解决方案
你可以试试java.net.HttpUrlConnection
,它对我有用,但实际上我通常使用 POST
HttpURLConnection connection = null;
BufferedReader reader = null;
String payload = "body";
try {
URL url = new URL("url endpoint");
if (url.getProtocol().equalsIgnoreCase("https")) {
connection = (HttpsURLConnection) url.openConnection();
} else {
connection = (HttpURLConnection) url.openConnection();
}
// Set connection properties
connection.setRequestMethod(method); // get or post
connection.setReadTimeout(3 * 1000);
connection.setDoOutput(true);
connection.setUseCaches(false);
if (payload != null) {
OutputStream os = connection.getOutputStream();
os.write(payload.getBytes(StandardCharsets.UTF_8));
os.flush();
os.close();
}
int responseCode = connection.getResponseCode();
}
推荐阅读
- apache - 使用 htaccess 重写商店搜索页面
- angular - Angular Ng2-charts 工具提示显示所有图例标记
- groovy - 如何使用 groovy 将 EDIFACT 消息(包含多个特殊字符和多行)放入变量中?
- api - 如何构建比特币钱包?
- javascript - 接受用户输入的 Javascript 程序
- azure - 如何在 Azure Devops 中检查某个日期的记录状态
- c# - 尽管在配置中设置了环境变量,但 Visual Studio for Mac 中出现了意外的空值
- reactjs - React 三 Fiber 使用 FBX 崩溃 react 组件
- sql - 如何在 PostgreSQL 中存储仓位顺序?
- serilog - 在 appsettings.json 中使用 Serilog,我在子记录器中的过滤器表达式不起作用