首页 > 解决方案 > 在 java/spring boot 中的 HTTP GET 请求中发送 JSON 正文

问题描述

我需要在 java/spring boot 中发送一个带有 json 正文的 GET 请求。我知道反对它的建议,但是我必须这样做有几个原因: 1. 我使用的第 3 方 API 只允许 GET 请求,所以 POST 不是一个选项。2. 我需要在正文中传递一个非常大的参数(大约 8-10k 个字符的逗号分隔列表),因此将查询参数附加到 url 上也不是一个选项。

我尝试了一些不同的东西:

  1. apache HttpClient from here: Send content body with HTTP GET Request in Java。这直接从 API 本身给出了一些关于错误密钥的错误。

  2. URIComponentsBuilder 从这里:Spring RestTemplate GET with parameters。这只是将参数添加到 url 上,正如我之前解释的那样,这不是一个选项。

  3. 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();
}

感谢您的帮助!

标签: javaspringspring-boot

解决方案


你可以试试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();
}

推荐阅读