繁体   English   中英

创建一个Java REST客户端以调用Spring Boot REST API

[英]Create a java REST client to call a spring boot REST API

我有一个仅使用POST JSON String的springboot项目,我正在使用gson将其转换为HashMap。 我使用Postman作为POST进行了测试,并使用诸如{'fistname': 'John', 'lastname' : 'Doe'}类的json字符串将主体添加为props ,转换为props = {'fistname': 'John', 'lastname' : 'Doe'} 它按预期工作

@RequestMapping(value = "/rest", method = RequestMethod.POST)
    protected String parse(@RequestParam("props") String props) {
    Gson gson = new Gson();
    Map<String, String> params = new HashMap<String, String>();
    params = gson.fromJson(props, Map.class);

    // Rest of the process
}

另一方面,我有一个JavaEE项目,需要调用此API

protected void callREST() {

      try {
            String json = someClass.getDate() //retrieved from database which is stored as json structure
            Map<String, String> props = gson.fromJson(json, Map.class);

            URL url = new URL("http://localhost:9090/myApp/rest");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");

            DataOutputStream wr = new DataOutputStream( conn.getOutputStream());

            System.out.println(props.toString());
            wr.writeBytes(json.toString());
            wr.flush();
            wr.close();
            if(conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException("Failed :: HTTP error code : " + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String output;
            System.out.println("Output from Server ... \n");
            while((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

       } catch(Exception e) {
          //print stack trace
       }
 }

我收到Failed :: HTTP error code : 400 我怀疑spring boot在POST请求之后没有收到props变量中的数据。 我应该在客户端代码中添加些什么来传递道具和数据,以使调用成功?

注意:JavaEE在tomcat上运行:8080,Springboot在不同tomcat上运行:9090

@RequestParam意味着服务器在请求URL http://localhost:9090/myApp/rest?param=.....中等待参数,但是在您的客户端中,您正在请求主体中编写JSON。

尝试在端点中使用@RequestBody批注

protected String parse(@RequestBody String props) {...}

您的资源希望获得表单参数(即,使用x-www-form-urlencoded编码的键值对),其中值恰好是JSON(尽管您发布的内容不是有效的JSON)。

但是您的客户端Java代码将内容类型设置为application / json,然后将JSON作为正文发送,而不是将其作为x-www-form-urlencoded正文的键“ props”的值发送。

这样就行不通了。

如果可以更改服务器,请执行此操作。 直接接受JSON作为正文:

@RequestMapping(value = "/rest", method = RequestMethod.POST)
public String parse(@RequestBody Map<String, String> map) {
     ...
}

如果不是,则需要发送正确的键值对,并确保该值已正确进行url编码。

暂无
暂无

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

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