【问题标题】:Create a java REST client to call a spring boot REST API创建 java REST 客户端以调用 Spring Boot REST API
【发布时间】:2018-01-24 20:44:17
【问题描述】:

我有一个 springboot 项目,它只需要使用 gson 将其转换为 HashMap 的 POST JSON 字符串。我使用 Postman 作为 POST 进行了测试,并将正文添加为 props,并使用像 {'fistname': 'John', 'lastname' : 'Doe'} 这样的 json 字符串,转换为 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 没有收到 props 变量中的数据,因为它是一个 POST 请求。 我应该在客户端代码中添加什么来传递道具和数据以使调用成功?

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

【问题讨论】:

  • 看看 Spring 的 RestTemplate 类,它对此非常有用。

标签: java spring-boot


【解决方案1】:

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

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

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

【讨论】:

  • 我怎样才能使这个异步?
【解决方案2】:

您的资源期望获取表单参数(即键值对,使用 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 编码的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2020-03-15
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多