相关疑难解决方法(0)

如何使用Spring RestTemplate发布表单数据?

我想将以下(工作)curl片段转换为RestTemplate调用:

curl -i -X POST -d "email=first.last@example.com" https://app.example.com/hr/email
Run Code Online (Sandbox Code Playgroud)

如何正确传递电子邮件参数?以下代码导致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 );
Run Code Online (Sandbox Code Playgroud)

我试图在PostMan中制定正确的调用,我可以通过将body参数指定为正文中的"form-data"参数来使其正常工作.在RestTemplate中实现此功能的正确方法是什么?

java rest spring resttemplate

124
推荐指数
3
解决办法
25万
查看次数

使用Spring Rest模板+ Spring Web MVC进行多部分文件上载

我正在尝试使用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);
Run Code Online (Sandbox Code Playgroud)

我有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
}
Run Code Online (Sandbox Code Playgroud)

我得到以下例外

 org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc resttemplate

34
推荐指数
5
解决办法
10万
查看次数

RestTemplate - 处理异常中的响应头/主体(RestClientException,HttpStatusCodeException)

在我的restful webservice中,如果出现错误请求(5xx)或4xx respose代码,我会在响应中写一个自定义标题"x-app-err-id".

在客户端,我使用RestTemplate的交换方法来进行RestFul Web服务调用.当响应代码为2xx时,一切都很好.

ResponseEntity<Component> response = restTemplate.exchange(webSvcURL,
    HttpMethod.POST, 
    requestEntity,
    Component.class);
Run Code Online (Sandbox Code Playgroud)

但是如果有异常(HttpStatusCodeException),因为它是一个错误的请求(5xx)或4xx,在HttpStatusCodeException的catch块中,我得到响应(见上文)为null,所以我没有访问我的自定义头我在我的网络服务中设置.如果RestTemplate中存在异常,如何从响应中获取自定义标头.

还有一个问题是,我在错误的情况下在响应体中设置了一个错误对象(json),我想知道如何在RestTemplate中出现异常时访问响应体

response resttemplate

28
推荐指数
2
解决办法
4万
查看次数

使用RestTemplate进行RESTful Services测试

在我的应用程序中,我有很多REST服务.我已经为所有服务编写了测试:

org.springframework.web.client.RestTemplate
Run Code Online (Sandbox Code Playgroud)

REST服务调用例如下所示:

final String loginResponse = restTemplate.exchange("http://localhost:8080/api/v1/xy", HttpMethod.POST, httpEntity, String.class)
        .getBody();
Run Code Online (Sandbox Code Playgroud)

然后我检查响应体 - 一切正常.缺点是必须启动应用程序才能调用REST服务.

我现在的问题是如何在JUnit- @Test方法中做到这一点?它是一个Spring Boot应用程序(带有嵌入式tomcat).

感谢帮助!

java rest junit spring-boot

12
推荐指数
3
解决办法
4万
查看次数

Spring RestTemplate - 重写ResponseErrorHandler

我打电话一个ReST通过服务RestTemplate,并试图覆盖ResponseErrorHandlerSpring 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");
   }
}
Run Code Online (Sandbox Code Playgroud)

Spring框架调用hasError方法但不调用handleError,所以我无法抛出自定义异常.在深入研究Spring RestTemplate源代码之后,我意识到handleResponseError方法中的代码导致了问题 - 它正在查找response.getStatusCoderesponse.getStatusText …

rest spring spring-mvc resttemplate

11
推荐指数
2
解决办法
5万
查看次数

Spring RestTemplate解析自定义错误响应

给定REST服务调用

http://acme.com/app/widget/123

收益:

<widget>
  <id>123</id>
  <name>Foo</name>
  <manufacturer>Acme</manufacturer>
</widget>
Run Code Online (Sandbox Code Playgroud)

此客户端代码有效:

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);
Run Code Online (Sandbox Code Playgroud)

但是,调用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>
Run Code Online (Sandbox Code Playgroud)

但是此客户端代码抛出异常:

Widget w = restTemplate.getForObject(
    "http://acme.com/app/widget/{id}", Widget.class, 456L);

org.springframework.web.client.HttpClientErrorException: 404 Not Found
Run Code Online (Sandbox Code Playgroud)

我试过了:

try {
    Widget w …
Run Code Online (Sandbox Code Playgroud)

rest spring-mvc

9
推荐指数
2
解决办法
1万
查看次数

Spring Rest客户端异常处理

我正在使用春天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();
    }
Run Code Online (Sandbox Code Playgroud)

如何获得ResponseWrapper例外情况?

我从这里开始阅读CustomRestTemplate,但无法确定哪一个最适合我的情况.ResponseExtractor

java rest spring rest-client

9
推荐指数
2
解决办法
2万
查看次数

try catch块的成本是多少?

好多了:

 if (condition) {
  try {
   //something
  } catch(SomeEx ex) {}
 }
Run Code Online (Sandbox Code Playgroud)

而不是这个:

 try {
   if (condition) {
     //something
   }
 } catch(SomeEx ex) {}
Run Code Online (Sandbox Code Playgroud)

当我进入try块时,JVM实际上做了什么?

编辑:我不想知道在第二个例子总是进去尝试...请回答问题.

java performance try-catch

7
推荐指数
1
解决办法
2882
查看次数

Rest模板自定义异常处理

我正在使用来自外部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 = …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc

7
推荐指数
1
解决办法
3万
查看次数

如何更改 Spring Boot 错误响应中的状态代码?

我正在制作一个简单的休息服务,它使用 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"
}
Run Code Online (Sandbox Code Playgroud)

我希望是这样

    "timestamp": "2019-07-01T17:56:04.539+0000",
    "status": 400,
    "error": "Internal Server Error",
    "message": "400 Bad Request",
    "path": "/8b8a38a9-a290-4560-84f6-3d4466e8d7901"
}
Run Code Online (Sandbox Code Playgroud)

它抛出 HttpClientErrorException.BadRequest 或 HttpClientErrorException.NotFound

我的代码是一个简单的端点:

    @GetMapping("/{id}")
    public MyModel getInfo(@PathVariable String id){
        return MyService.getInfo(id);
    }
Run Code Online (Sandbox Code Playgroud)

java rest spring controller spring-boot

6
推荐指数
1
解决办法
8619
查看次数

请解释RestTemplate

我上课了

public class Client extends RestTemplate
// org.springframework.web.client.RestTemplate
Run Code Online (Sandbox Code Playgroud)

RestTemplate用于什么?

java spring resttemplate

5
推荐指数
1
解决办法
1万
查看次数

如何将RestTemplate与多种响应类型一起使用?

我正在使用spring RestTemplatexmlwebservice后端进行通信,如下所示:

ResponseEntity<MainDTO> dto = restTemplate.postForObject(url, postData, MainDTO.class);
Run Code Online (Sandbox Code Playgroud)

问题:后端可能会响应MainDTO正常数据或ErrorDTO出现故障.但两者兼而有之HTTP 200.

但我不知道之前会有哪些物体回来!无论如何restTemplate要求我class之前通过这种类型.

那么,我怎么能将xml解析为普通或错误bean?

旁注:我对webservice后端没有任何控制权.

java spring spring-rest

5
推荐指数
1
解决办法
7454
查看次数

如何在记录 RestTemplate 生成的异常时打印完整的错误消息?

我们有一个基于 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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": …
Run Code Online (Sandbox Code Playgroud)

java error-handling spring resttemplate spring-boot

5
推荐指数
1
解决办法
1902
查看次数