如果使用RestTemplate方法返回null被嘲笑,可能是因为没有正确处理异常或请求失败的情况。以下是一个解决方法的示例代码:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
@Component
public class MyRestClient {
private RestTemplate restTemplate;
public MyRestClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getDataFromApi(String url) {
try {
ResponseEntity response = restTemplate.getForEntity(url, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
return response.getBody();
} else {
// 请求失败
throw new RuntimeException("请求失败,状态码:" + response.getStatusCode());
}
} catch (HttpServerErrorException e) {
// 服务器错误
throw new RuntimeException("服务器错误:" + e.getResponseBodyAsString());
} catch (Exception e) {
// 其他异常
throw new RuntimeException("请求异常:" + e.getMessage());
}
}
}
在上面的代码示例中,我们通过try-catch块来处理可能发生的异常情况。如果请求成功并返回状态码为200,则返回响应体的内容。如果请求失败,我们抛出一个RuntimeException,并提供响应的状态码。如果服务器返回5xx错误,我们也抛出一个RuntimeException,并提供错误消息。
这样处理请求异常可以避免返回null,而是提供有用的错误信息,使得调用方能够更好地处理异常情况。