我想将以下(工作)curl片段转换为RestTemplate调用:
curl -i -X POST -d "email=first.last@example.com" https://app.example.com/hr/email
如何正确传递电子邮件参数?以下代码导致404 Not Found响应:
String url = "https://app.example.com/hr/email";
Map<String, String> params = new HashMap<String, String>();
params.put("email", "first.last@example.com");
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity( url, params, String.class );
我试图在PostMan中制定正确的调用,我可以通过将body参数指定为正文中的"form-data"参数来使其正常工作.在RestTemplate中实现此功能的正确方法是什么?
我正在尝试使用RestTemplate上传一个文件,代码如下.
   MultiValueMap<String, Object> multipartMap = new LinkedMultiValueMap<>();
   multipartMap.add("file", new ClassPathResource(file));
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(new MediaType("multipart", "form-data"));
   HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(multipartMap, headers);
   System.out.println("Request for File Upload : " + request);
   ResponseEntity<byte[]> result = template.get().exchange(
                    contextPath.get() + path, HttpMethod.POST, request,
                    byte[].class);
我有MultipartResolverbean和Controller代码
@RequestMapping(value = "/{id}/image", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
@Transactional(rollbackFor = Exception.class)
public byte[] setImage(@PathVariable("id") Long userId,
        @RequestParam("file") MultipartFile file) throws IOException {
    // Upload logic
}
我得到以下例外
 org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not …在我的restful webservice中,如果出现错误请求(5xx)或4xx respose代码,我会在响应中写一个自定义标题"x-app-err-id".
在客户端,我使用RestTemplate的交换方法来进行RestFul Web服务调用.当响应代码为2xx时,一切都很好.
ResponseEntity<Component> response = restTemplate.exchange(webSvcURL,
    HttpMethod.POST, 
    requestEntity,
    Component.class);
但是如果有异常(HttpStatusCodeException),因为它是一个错误的请求(5xx)或4xx,在HttpStatusCodeException的catch块中,我得到响应(见上文)为null,所以我没有访问我的自定义头我在我的网络服务中设置.如果RestTemplate中存在异常,如何从响应中获取自定义标头.
还有一个问题是,我在错误的情况下在响应体中设置了一个错误对象(json),我想知道如何在RestTemplate中出现异常时访问响应体
在我的应用程序中,我有很多REST服务.我已经为所有服务编写了测试:
org.springframework.web.client.RestTemplate
REST服务调用例如下所示:
final String loginResponse = restTemplate.exchange("http://localhost:8080/api/v1/xy", HttpMethod.POST, httpEntity, String.class)
        .getBody();
然后我检查响应体 - 一切正常.缺点是必须启动应用程序才能调用REST服务.
我现在的问题是如何在JUnit- @Test方法中做到这一点?它是一个Spring Boot应用程序(带有嵌入式tomcat).
感谢帮助!
我打电话一个ReST通过服务RestTemplate,并试图覆盖ResponseErrorHandler在Spring 3.2处理自定义错误代码.
CustomResponseErrroHandler
public class MyResponseErrorHandler implements ResponseErrorHandler {
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        boolean hasError = false;
        int rawStatusCode = response.getRawStatusCode();
        if (rawStatusCode != 200){
            hasError = true;
        }
        return hasError;
     }
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        //String body = IOUtils.toString(response.getBody());
        throw new CustomServiceException(response.getRawStatusCode() , "custom Error");
   }
}
Spring框架调用hasError方法但不调用handleError,所以我无法抛出自定义异常.在深入研究Spring RestTemplate源代码之后,我意识到handleResponseError方法中的代码导致了问题 - 它正在查找response.getStatusCode或response.getStatusText …
给定REST服务调用
http://acme.com/app/widget/123
收益:
<widget>
  <id>123</id>
  <name>Foo</name>
  <manufacturer>Acme</manufacturer>
</widget>
此客户端代码有效:
RestTemplate restTemplate = new RestTemplate();
XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
xStreamMarshaller.getXStream().processAnnotations(
    new Class[] { 
        Widget.class,
        ErrorMessage.class
    });
HttpMessageConverter<?> marshallingConverter = new MarshallingHttpMessageConverter(
    xStreamMarshaller, xStreamMarshaller);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(marshallingConverter);
restTemplate.setMessageConverters(converters);
Widget w = restTemplate.getForObject(
    "http://acme.com/app/widget/{id}", Widget.class, 123L);
但是,调用http://acme.com/app/widget/456会返回:
<error>
    <message>Widget 456 does not exist</message>
    <timestamp>Wed, 12 Mar 2014 10:34:37 GMT</timestamp>
</error>
但是此客户端代码抛出异常:
Widget w = restTemplate.getForObject(
    "http://acme.com/app/widget/{id}", Widget.class, 456L);
org.springframework.web.client.HttpClientErrorException: 404 Not Found
我试过了:
try {
    Widget w …我正在使用春天RestTemplate来消耗休息服务(在春季休息时暴露).我能够消耗成功的场景.但对于负面情况,服务会返回错误消息和错误代码.我需要在我的网页中显示这些错误消息.
例如,对于无效请求,服务会抛出HttpStatus.BAD_REQUEST适当的消息.如果我把try-catch块转到catch块而我无法得到ResponseEntity对象.
try {
    ResponseEntity<ResponseWrapper<MyEntity>> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, entity,
        new ParameterizedTypeReference<ResponseWrapper<MyEntity>>() {
    });
    responseEntity.getStatusCode();
    } catch (Exception e) {
        //TODO How to get response here, so that i can get error messages?
        e.printStackTrace();
    }
如何获得ResponseWrapper例外情况?
我从这里开始阅读CustomRestTemplate,但无法确定哪一个最适合我的情况.ResponseExtractor
好多了:
 if (condition) {
  try {
   //something
  } catch(SomeEx ex) {}
 }
而不是这个:
 try {
   if (condition) {
     //something
   }
 } catch(SomeEx ex) {}
当我进入try块时,JVM实际上做了什么?
编辑:我不想知道在第二个例子总是进去尝试...请回答问题.
我正在使用来自外部API的一些REST端点,我正在使用Rest Template接口来实现此目的.当我从这些调用中收到某些HTTP状态代码时,我希望能够抛出自定义应用程序异常.为了实现它,我正在实现ResponseErrorHandler接口,如下所示:
public class MyCustomResponseErrorHandler implements ResponseErrorHandler {
    private ResponseErrorHandler myErrorHandler = new DefaultResponseErrorHandler();
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return myErrorHandler.hasError(response);
    }
    public void handleError(ClientHttpResponse response) throws IOException {
        String body = IOUtils.toString(response.getBody());
        MyCustomException exception = new MyCustomException(response.getStatusCode(), body, body);
        throw exception;
    }
}
public class MyCustomException extends IOException {
    private HttpStatus statusCode;
    private String body;
    public MyCustomException(String msg) {
        super(msg);
        // TODO Auto-generated constructor stub
    }
    public MyCustomException(HttpStatus statusCode, String body, String msg) {
        super(msg);
        this.statusCode = …我正在制作一个简单的休息服务,它使用 RestTemplate 进行一些 http 调用并聚合数据。
有时我会收到 NotFound 错误,有时会收到 BadRequest 错误。
我想用相同的状态代码响应我的客户端,Spring 似乎已经提供了这种开箱即用的映射。消息正常,但状态代码始终为 500 内部服务器错误。
我想将我的状态代码映射到我最初收到的状态代码
    "timestamp": "2019-07-01T17:56:04.539+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "400 Bad Request",
    "path": "/8b8a38a9-a290-4560-84f6-3d4466e8d7901"
}
我希望是这样
    "timestamp": "2019-07-01T17:56:04.539+0000",
    "status": 400,
    "error": "Internal Server Error",
    "message": "400 Bad Request",
    "path": "/8b8a38a9-a290-4560-84f6-3d4466e8d7901"
}
它抛出 HttpClientErrorException.BadRequest 或 HttpClientErrorException.NotFound
我的代码是一个简单的端点:
    @GetMapping("/{id}")
    public MyModel getInfo(@PathVariable String id){
        return MyService.getInfo(id);
    }
我上课了
public class Client extends RestTemplate
// org.springframework.web.client.RestTemplate
RestTemplate用于什么?
我正在使用spring RestTemplate与xmlwebservice后端进行通信,如下所示:
ResponseEntity<MainDTO> dto = restTemplate.postForObject(url, postData, MainDTO.class);
问题:后端可能会响应MainDTO正常数据或ErrorDTO出现故障.但两者兼而有之HTTP 200.
但我不知道之前会有哪些物体回来!无论如何restTemplate要求我class之前通过这种类型.
那么,我怎么能将xml解析为普通或错误bean?
旁注:我对webservice后端没有任何控制权.
我们有一个基于 Spring-Boot (2.3.10.RELEASE) 的应用程序,它使用RestTemplate.
如果任何 REST API 返回任何 4xx 或 5xx HTTP 错误代码以及消息正文,则不会记录完整的消息正文。
这是一个最小的可重现示例:
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
@Slf4j
public class RestTemplateTest {
    @Test
    void shouldPrintErrorForRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        try {
            restTemplate.getForEntity("http://hellosmilep.free.beeceptor.com/error/notfound", String.class);
        } catch (Exception e) {
            log.error("Error calling REST API", e);
        }
    }
}
输出:
10:28:11.347 [main] ERROR com.smilep.java.webapp.RestTemplateTest - Error calling REST API
org.springframework.web.client.HttpClientErrorException$NotFound: 404 Not Found: [{
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": …java ×9
spring ×9
rest ×6
resttemplate ×6
spring-mvc ×4
spring-boot ×3
controller ×1
junit ×1
performance ×1
response ×1
rest-client ×1
spring-rest ×1
try-catch ×1