java-如何将数据从servlet发送到REST API

前端之家收集整理的这篇文章主要介绍了java-如何将数据从servlet发送到REST API 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

最佳答案
或者,您必须使用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);
原文链接:https://www.f2er.com/java/532899.html

猜你在找的Java相关文章