简体   繁体   English

具有负载的Java RESTful Web服务POST

[英]Java RESTful webservice-POST with payload

The input I have are a URL and a request payload. 我输入的内容是URL和请求有效负载。

Say, URL: https://somesresource.com Payload: {userId: "4566"} 说,URL: https://somesresource.com ://somesresource.com有效负载:{userId:“ 4566”}

The output I get back is a Json with several key-value pairs. 我得到的输出是带有几个键值对的Json。

I tried doing this in Rest Console and the output(Json) looked good. 我尝试在Rest Console中执行此操作,并且output(Json)看起来不错。 But, when I try to run the following program the output is not the json but the file(html i suppose) from the URL's server. 但是,当我尝试运行以下程序时,输出的不是json,而是URL服务器的文件(我想是html)。 How do I retrieve the Json instead of the file? 如何检索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();
    }

I think you are missing a converter in your application. 我认为您在应用程序中缺少转换器。 I use RestFul Web service with Spring and use MappingJacksonHttpMessageConverter for to & fro conversion of JSON. 我将RestFul Web服务与Spring一起使用,并将MappingJacksonHttpMessageConverter用于JSON的来回转换。 Please provide more details of your configuration if you are looking for a specific answer. 如果您正在寻找特定的答案,请提供您的配置的更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM