如何在Spring Boot中使用RestTemplate将参数作为POST请求传递到端点?

huangapple go评论111阅读模式
英文:

How can I pass parameter as post to endpoint using RestTemplate in springboot?

问题

I am using RestTemplate in my project to make a post request to an endpoint. Basically I have lambda function written in nestjs. I am injecting lambda service in my java project. If vehicleName if condition passes, I would like to POST that vehicleName to the url. Is there any suggestions on how I can achieve this?

Here is my code:

  1. private void callLambdaService(String vehicleTypesParamValue)
  2. {
  3. final String url = "http://localhost:3000/dispatcher/service/api/message";
  4. final String zMETHOD = "callLambdaService - ";
  5. RestTemplate restTemplate = new RestTemplate();
  6. restTemplate.exchange(url, HttpMethod.POST, vehicleName, String.class);
  7. HttpHeaders headers = new HttpHeaders();
  8. headers.setContentType(MediaType.APPLICATION_JSON);
  9. String result = restTemplate.getForObject(url, String.class);
  10. VehicleType vehicleName=null;
  11. String[] vehicleTypes = vehicleTypesParamValue.split(",");
  12. Set<VehicleType> results = new HashSet<>();
  13. try
  14. {
  15. for (String vehicleTypeParam : vehicleTypes)
  16. {
  17. vehicleName =
  18. vehicleTypeFactory.getVehicleTypeByIspName(
  19. vehicleTypeParam);
  20. if (vehicleName == null)
  21. {
  22. LOGGER.warn("No codes for products or vehicle types were supplied");
  23. }
  24. else if (vehicleName.equals("US Mutual Fund"))
  25. {
  26. LOGGER.info(zMETHOD + "Vehicles provided: "
  27. + vehicleName.getIspName());
  28. }
  29. else
  30. {
  31. LOGGER.warn(
  32. String.format("Unknown vehicle type provided: [%s]",
  33. vehicleName.getIspName()));
  34. }
  35. }
  36. }catch (Exception e) {
  37. LOG.error("Unable to get vehicletype data", e);
  38. }
  39. }

And the testing command:

  1. curl -X POST "https://gdxdispatcher.dev.awstrp.net/dispatcher/service/api/message" -H "accept: */*" -H "Content-Type: application/json" -d "{\"vehicleType\":\"US Mutual Fund,VIP\",\"source\":\"PCS_DATACACHE_TOPIC\"}"
英文:

I am using RestTemplate in my project to make a post request to an endpoint. Basically I have lambda function written in nestjs. I am injecting lambda service in my java project. If vehicleName if condition passes, I would like to POST that vehicleName to the url. Is there any suggestions on how I can achieve this? I would be testing my application using this command

  1. curl -X POST &quot;https://gdxdispatcher.dev.awstrp.net/dispatcher/service/api/message&quot; -H &quot;accept: */*&quot; -H &quot;Content-Type: application/json&quot; -d &quot;{\&quot;vehicleType\&quot;:\&quot;US Mutual Fund,VIP\&quot;,\&quot;source\&quot;:\&quot;PCS_DATACACHE_TOPIC\&quot;}&quot;

Here is my code

  1. private void callLambdaService(String vehicleTypesParamValue)
  2. {
  3. final String url = &quot;http://localhost:3000/dispatcher/service/api/message&quot;;
  4. final String zMETHOD = &quot;callLambdaService - &quot;;
  5. RestTemplate restTemplate = new RestTemplate();
  6. restTemplate.exchange(&quot;url&quot;, HttpMethod.POST, vehicleName, String.class);
  7. HttpHeaders headers = new HttpHeaders();
  8. headers.setContentType(MediaType.APPLICATION_JSON);
  9. String result = restTemplate.getForObject(url, String.class);
  10. VehicleType vehicleName=null;
  11. String[] vehicleTypes = vehicleTypesParamValue.split(&quot;,&quot;);
  12. Set&lt;VehicleType&gt; results = new HashSet&lt;&gt;();
  13. try
  14. {
  15. for (String vehicleTypeParam : vehicleTypes)
  16. {
  17. vehicleName =
  18. vehicleTypeFactory.getVehicleTypeByIspName(
  19. vehicleTypeParam);
  20. if (vehicleName == null)
  21. {
  22. LOGGER.warn(&quot;No codes for products or vehicle types were supplied&quot;);
  23. }
  24. else if (vehicleName.equals(&quot;US Mutual Fund&quot;))
  25. {
  26. LOGGER.info(zMETHOD + &quot;Vehicles provided: &quot;
  27. + vehicleName.getIspName());
  28. }
  29. else
  30. {
  31. LOGGER.warn(
  32. String.format(&quot;Unknown vehicle type provided: [%s]&quot;,
  33. vehicleName.getIspName()));
  34. }
  35. }
  36. }catch (Exception e) {
  37. LOG.error(&quot;Unable to get vehicletype data&quot;, e);
  38. }
  39. }
  40. </details>
  41. # 答案1
  42. **得分**: 1
  43. 1. 创建一个表示HTTP请求的数据结构的 **headers**。
  44. ```java
  45. HttpHeaders headers = new HttpHeaders();
  46. headers.setContentType(MediaType.APPLICATION_JSON);
  1. org.json 包中创建一个可修改的名称/值映射集合的 JSONObject,并放入名称和值。

    1. JSONObject requestBody = new JSONObject();
    2. requestBody.put("vehicleType", "US Mutual Fund,VIP");
    3. requestBody.put("source", "PCS_DATACACHE_TOPIC");
  2. 创建代表HTTP请求或响应的 HttpEntity,在这种情况下,请求由headers和body组成。

    1. HttpEntity<String> request = new HttpEntity<>(requestBody.toString(), headers);
  3. 通过 posting 对象到给定的URI模板来创建一个新的资源。它将结果自动转换为responseType参数中指定的类型。然后,我们将ObjectNode定义为我们的资源,响应类型定义为我们的结果。

    1. ObjectNode result = restTemplate.postForObject("https://gdxdispatcher.dev.awstrp.net/dispatcher/service/api/message", request, ObjectNode.class);
英文:

Well, following the instructions:

  1. Create headers which will be a data structure representing HTTP request.

    1. HttpHeaders headers = new HttpHeaders();
    2. headers.setContentType(MediaType.APPLICATION_JSON);
  2. Build a JSONObject from org.json package that is a modifiable set of name/value mappings and put names and values.

    1. JSONObject requestBody = new JSONObject();
    2. requestBody.put(&quot;vehicleType&quot;, &quot;US Mutual Fund,VIP&quot;);
    3. requestBody.put(&quot;source&quot;, &quot;PCS_DATACACHE_TOPIC&quot;);
  3. Create our HttpEntity that represents an HTTP request or response, in this case request consisting of headers and body.

    1. HttpEntity&lt;String&gt; request = new HttpEntity&lt;&gt;(requestBody.toString(), headers);
  4. Create a new resource by posting an object to the given URI template.
    It returns the result as automatically converted to the type specified in the responseType parameter.
    Then we define a ObjectNode as our resource and response type as our result.

    1. ObjectNode result = restTemplate.postForObject(&quot;https://gdxdispatcher.dev.awstrp.net/dispatcher/service/api/message&quot;,
    2. request, ObjectNode.class);

huangapple
  • 本文由 发表于 2020年1月4日 00:20:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定