如何将数据从Servlet发送到Rest API

时间:2019-04-04 10:18:05

标签: java rest servlets

我想将数据从servlet发送到rest api。 它是怎么做到的:

protected void doPost(
      HttpServletRequest  request
    , HttpServletResponse response
) throws ServletException, IOException {

    String Id= "MyId";

    response.setContentType("application/json");
    response.getWriter().write(Id);
    getServletContext()
        .getRequestDispatcher("<PathofAPI>")
        .forward(request, response);
}

发送完数据后,如何在我的剩余api中检索数据

2 个答案:

答案 0 :(得分:2)

或者,您必须使用getter和setter为您的Id参数创建POJO类:

String createRequestUrl="YOUR_LINK WHERE_YOU GET answer FROM";
RestTemplate template=new RestTemplate();
your_POJO_object.setYour_Pojo_Object(Id);
ObjectMapper objectMapper = new ObjectMapper();
MultiValueMap<String, String> orderRequestHeaders=new 
LinkedMultiValueMap<String,String>();
orderRequestHeaders.add("Content-Type", "application/json");
orderRequestHeaders.add("Accept", "application/json");
String orderCreateRequest=objectMapper.writeValueAsString(YOUR POJO object.class);
HttpEntity<String> orderRequest=new HttpEntity<String>(orderCreateRequest, orderRequestHeaders);
String response=template.postForObject(createRequestUrl, orderRequest, String.class);

答案 1 :(得分:0)

您想达到的目标对我来说还不清楚。

通过在响应中写入“ MyId”,然后再让“ PathofServet”处理请求,就破坏了响应中的json格式。

您是否希望servlet“ PathofServlet”作为请求并作为响应发送?您希望servlet响应什么?