java - 创建一个java REST客户端来调用spring boot REST API

标签 java spring-boot

我有一个 springboot 项目,只需要 POST JSON 字符串,我使用 gson 将其转换为 HashMap。我使用 Postman 作为 POST 进行了测试,并将正文添加为 props ,并使用 json 字符串,如 {'fistname': 'John', 'lastname' : 'Doe'},翻译为 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
       }
 }

我收到失败::HTTP 错误代码:400。我怀疑 Spring Boot 没有接收到 props 变量中的数据,因为它是 POST 请求。 我应该在客户端代码中添加什么来传递 Prop 和数据以使此调用成功?

Note: JavaEE is running on tomcat :8080, Springboot is running on different tomcat :9090

最佳答案

@RequestParam 表示服务器等待请求 URL 中的参数 http://localhost:9090/myApp/rest?param=..... 但在您的客户端中您正在请求正文中编写 JSON。

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

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

关于java - 创建一个java REST客户端来调用spring boot REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718088/

相关文章:

java - spring boot 无法使用 Intellij 连接 MYSQL 数据库

java - (Spring boot)Optional<>Class可以像List<>Class一样吗?

java - 如何通过比较同一行上的三个变量来返回 boolean 值?

java - 过滤映射并返回键列表

java - ClassNotFoundException : org. jboss.resteasy.client.jaxrs.ResteasyClientBuilder 错误

maven - 如何从 Java (Spring boot) 应用程序向 Prometheus 公开指标

java - Docx4j - 文档中的图像

java - 通过索引查找数组中的对象引用

java - 加入 hql hibernate 的预期路径

java - Spring @Value 未正确解析