Java RestTemplate如何使用请求体进行POST。

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

Java RestTemplate how to POST with body

问题

我需要一些关于在RestController中使用RestTemplate正确POST JSON主体的帮助。我只是不够熟悉我所做的错误之处。我已经花了太多时间看这个,但没有得到我需要的结果。希望我提供的信息是清楚的。目前,我只是尝试将JSON主体POST到以下URL API。

CONTROLLER

@RestController
@RequestMapping("/api/feedback")
public class FeedbackController {

  private final RestTemplate restTemplate;

  @Autowired
  public FeedbackController(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
  }
  
  @RequestMapping(
    method = RequestMethod.POST
  )
  public IncidentReport createIncident()  
  {  
	  
    return restTemplate.exchange(
    	"URL_API/create",
        HttpMethod.POST, null,
        new ParameterizedTypeReference<IncidentReport>(){}
    ).getBody();
  } 
}

JSON POST BODY

{
  "group": "my_group",
  "short_description": "this is a test for the short description",
  "contact_type": "Alert"
}
英文:

I need some assistance on the correct way to POST a json body with RestTemplate within a RestController. I am just not familiar enough as to what I am doing wrong. I have spent to much time looking at this and I am not getting the result I need. Hopefully the info I provide is clear. As of right now I am just trying to POST the JSON body to the below URL API

CONTROLLER

@RestController
@RequestMapping(&quot;/api/feedback&quot;)
public class FeedbackController {

  private final RestTemplate restTemplate;

  @Autowired
  public FeedbackController(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
  }
  
  @RequestMapping(		  	
			method = RequestMethod.POST
			)
  public IncidentReport createIncident()	  
  {  
	  
    return restTemplate.exchange(
    	&quot;URL_API/create&quot;,
        HttpMethod.POST, null,
        new ParameterizedTypeReference&lt;IncidentReport&gt;(){}
    			
    ).getBody();
  } 

JSON POST BODY

 {
&quot;group&quot;: &quot;my_group&quot;,
&quot;short_description&quot;:&quot;this is a test for the short description&quot;,
&quot;contact_type&quot;:&quot;Alert&quot;,
 }

答案1

得分: 1

exchange 是低级方法,通常更具体的方法在覆盖您的用例的情况下通常更友好。如果您需要头信息,您可以使用 postForEntity(如果需要头信息):

return restTemplate.postForObject(url, incidentObject, IncidentReport.class);
英文:

exchange is the low-level method, and the more specific ones are usually more friendly as long as they cover your use case. You're looking for a postForObject (postForEntity if you need the headers):

return restTemplate.postForObject(url, incidentObject, IncidentReport.class);

答案2

得分: -1

StackTrace会更有帮助。我认为你应该以以下方式实例化RestTemplate。

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder
            .setConnectTimeout(Duration.ofMillis(3000))
            .setReadTimeout(Duration.ofMillis(3000))
            .build();
}

然后在你的Controller类中自动装配它。

@Autowired
private RestTemplate myRestTemplate;

确保在类路径中存在Jackson库。尝试使用myRestTemplate.postForObject()。这没有太多复杂性。如果仍然遇到问题,请尝试分析堆栈跟踪,你将会得到一些提示。

英文:

StackTrace would have been more helpful. I think you should instantiate RestTemplate in below manner.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder
            .setConnectTimeout(Duration.ofMillis(3000))
            .setReadTimeout(Duration.ofMillis(3000))
            .build();
}

Then AutoWire it in your Controller class

 @Autowired
private RestTemplate myRestTemplate;

Ensure Jackson library is present in the classpath. Try to use myRestTemplate.postForObject(). There is not much to this. If you are still getting an issue try to analyze stack trace, you will get some hint.

答案3

得分: -1

Sure, here's the translated content:

由于Spring Boot自动配置了RestTemplateObjectMapper来序列化/反序列化您的@RestController端点中的数据,您完全不必坚持使用RestTemplate,可以像以下代码片段中所示使用功能:

@RestController
@RequestMapping("/api/feedback")
public class FeedbackController {

    @Autowired private FeedbackFacade feedbackFacade;

    @PostMapping("/")
    public ResponseEntity<IncidentReport> createIncidentReport(
            @RequestBody IncidentReport incidentReport)
    {
        log.info("Create incident report {}", incidentReport);
        var createdIncidentReport = feedbackFacade.create(incidentReport);
        log.info("Created incident report: {}", createdIncidentReport);
        return new ResponseEntity<>(createdIncidentReport, HttpStatus.CREATED);
    }
}

Please note that the code has been translated into Chinese.

英文:

Since spring boot autoconfigures RestTemplate and ObjectMapper to serialize/deserialize in your @RestController endpoints you don't have to stick with RestTemplate at all and can use functionality as show in the following code snippet:

@RestController
@RequestMapping(&quot;/api/feedback&quot;)
public class FeedbackController {

    @Autowired private FeedbackFacade feedbackFacade;

    @PostMapping(&quot;/&quot;)
    public ResponseEntity&lt;IncidentReport&gt; createIncidentReport(
            @RequestBody IncidentReport incidentReport)
    {
        log.info(&quot;Create incident report {}&quot;, incidentReport);
        var createdIncidentReport = feedbackFacade.create(incidentReport);
        log.info(&quot;Created incident report: {}&quot;, createdIncidentReport);
        return new ResponseEntity&lt;&gt;(createdIncidentReport, HttpStatus.CREATED)
    }
}

huangapple
  • 本文由 发表于 2020年7月28日 09:15:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63125700.html
匿名

发表评论

匿名网友

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

确定