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

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

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:

private void callLambdaService(String vehicleTypesParamValue)
{
    final String url = "http://localhost:3000/dispatcher/service/api/message";

    final String zMETHOD = "callLambdaService - ";

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.exchange(url, HttpMethod.POST, vehicleName, String.class);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    String result = restTemplate.getForObject(url, String.class);

    VehicleType vehicleName=null;

    String[] vehicleTypes = vehicleTypesParamValue.split(",");
    Set<VehicleType> results = new HashSet<>();
    try
    {
        for (String vehicleTypeParam : vehicleTypes)
        {
            vehicleName =
                    vehicleTypeFactory.getVehicleTypeByIspName(
                            vehicleTypeParam);
            if (vehicleName == null)
            {
                LOGGER.warn("No codes for products or vehicle types were supplied");
            }
            else if (vehicleName.equals("US Mutual Fund"))
            {
                LOGGER.info(zMETHOD + "Vehicles provided: "
                        + vehicleName.getIspName());

            }
            else
            {
                LOGGER.warn(
                        String.format("Unknown vehicle type provided: [%s]",
                                vehicleName.getIspName()));
            }

        }
    }catch (Exception e) {
        LOG.error("Unable to get vehicletype data", e);
    }

}

And the testing command:

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

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


private void callLambdaService(String vehicleTypesParamValue)
{
final String url = &quot;http://localhost:3000/dispatcher/service/api/message&quot;;
final String zMETHOD = &quot;callLambdaService - &quot;;
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange(&quot;url&quot;, HttpMethod.POST, vehicleName, String.class);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String result = restTemplate.getForObject(url, String.class);
VehicleType vehicleName=null;
String[] vehicleTypes = vehicleTypesParamValue.split(&quot;,&quot;);
Set&lt;VehicleType&gt; results = new HashSet&lt;&gt;();
try
{
for (String vehicleTypeParam : vehicleTypes)
{
vehicleName =
vehicleTypeFactory.getVehicleTypeByIspName(
vehicleTypeParam);
if (vehicleName == null)
{
LOGGER.warn(&quot;No codes for products or vehicle types were supplied&quot;);
}
else if (vehicleName.equals(&quot;US Mutual Fund&quot;))
{
LOGGER.info(zMETHOD + &quot;Vehicles provided: &quot;
+ vehicleName.getIspName());
}
else
{
LOGGER.warn(
String.format(&quot;Unknown vehicle type provided: [%s]&quot;,
vehicleName.getIspName()));
}
}
}catch (Exception e) {
LOG.error(&quot;Unable to get vehicletype data&quot;, e);
}
}
</details>
# 答案1
**得分**: 1
1. 创建一个表示HTTP请求的数据结构的 **headers**。
```java
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
  1. org.json 包中创建一个可修改的名称/值映射集合的 JSONObject,并放入名称和值。

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

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

    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.

     HttpHeaders headers = new HttpHeaders();
    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.

     JSONObject requestBody = new JSONObject();
    requestBody.put(&quot;vehicleType&quot;, &quot;US Mutual Fund,VIP&quot;);
    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.

     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.

     ObjectNode result = restTemplate.postForObject(&quot;https://gdxdispatcher.dev.awstrp.net/dispatcher/service/api/message&quot;, 
    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:

确定