【问题标题】:Java RESTful webservice-POST with payload带有有效负载的 Java RESTful webservice-POST
【发布时间】:2025-12-04 17:15:02
【问题描述】:

我的输入是一个 URL 和一个请求负载。

说, 网址:https://somesresource.com 有效负载:{userId:“4566”}

我得到的输出是一个带有多个键值对的 Json。

我尝试在 Rest Console 中执行此操作,并且输出(Json)看起来不错。但是,当我尝试运行以下程序时,输出不是 json,而是来自 URL 服务器的文件(我想是 html)。如何检索 Json 而不是文件?

@Transactional
    @RequestMapping(value = "/xxx", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    String consumer() throws Exception {

        String line;
        String userId = "12345";
        StringBuffer jsonString = new StringBuffer();
        URL url = new URL("https://somewebsite/userprofile");
        String payload="{\"userId\":\""+sid+"\"}";
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        try {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            writer.write(payload);
            writer.close();
            System.out.print(connection.getInputStream().toString());
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
            connection.disconnect();
        }
        catch(Exception e) {

        }
        return jsonString.toString();
    }

【问题讨论】:

    标签: java json spring rest spring-mvc


    【解决方案1】:

    我认为您的应用程序中缺少转换器。我将 RestFul Web 服务与 Spring 一起使用,并使用 MappingJacksonHttpMessageConverter 进行 JSON 的来回转换。如果您正在寻找具体的答案,请提供您的配置的更多详细信息。

    【讨论】:

      最近更新 更多