如何将数据从servlet发送到rest api

问题描述 投票:3回答:2

我想将数据从我的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中检索它

java rest servlets
2个回答
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);

0
投票

你想要达到的目标对我来说有点不清楚。

通过在让“PathofServet”处理请求之前将“MyId”写入响应,您将在响应中断开json格式。

你有一个servlet“PathofServlet”的例子,期望作为请求并作为响应发送吗?您希望您的servlet做出什么回应?

© www.soinside.com 2019 - 2024. All rights reserved.