如何在春季启动时修复RestTemplate NullPointerException?

时间:2019-06-07 09:14:10

标签: java rest spring-boot

var params =  {
            "callback_url": "https://mywebsite.com/responseHandler",
            "source": "puts 'Hello World'",
            "lang": 8,
            "testcases": "[\"This is input 1\", \"This is input 2\"]",
            "wait": false,
            "format": "json"
          }
        var config = {
            mode: "no-cors",
            headers: {
                "X-RapidAPI-Host": "hackerrank-hackerrank.p.rapidapi.com",
                "X-RapidAPI-Key": "a72a0f1b5dmshdc3f55e233876eap1b8939jsnffad2a5b6e6e",
                'Access-Control-Allow-Origin': '*',
                "Content-Type": "application/x-www-form-urlencoded"
            }
        }
        axios.post("https://hackerrank-hackerrank.p.rapidapi.com/https://api.hackerrank.com/checker/submission.json", params, config)
            .catch((error) => {
                console.log(error.message);
            })
            .then((response) => {
                console.log(response);
            })
@Service
public class RequestSender {

    private static final Logger logger = LoggerFactory.getLogger(RequestSender.class);

    @Autowired
    private RestTemplate restTemplate;

    public MbsFtResponseData sendJsonDataToMBS(final MBSTransactionData transactionData) {
        String mbsUrl = MBSConfigConstants.mbsUrl;
        try {
            logger.info("Sending request method Is Initiated");
            HttpEntity<MBSTransactionData> httpEntity = new HttpEntity<>(transactionData);
            ResponseEntity<MbsFtResponseData> response = restTemplate.exchange(mbsUrl, HttpMethod.POST, httpEntity,
                    MbsFtResponseData.class);
            if (response != null) {
                HttpStatus status = response.getStatusCode();
                if (status.is2xxSuccessful()) {
                    logger.info("Response getting back is succeded with the status code {}", status.value());
                    return response.getBody();
                } else {
                    logger.error("ERROR Response getting back is  with the status code {}", status.value());
                    throw new BBPSMBSException("Error is while connecting to mBS server", status.value());
                }
            } else {
                logger.error("Null value::::::::::::response is null");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ERROR :::{}:: is occered ", e.getCause());
        }
        return new MbsFtResponseData("Server Not responding or Busy", 500, "FAILED");
    }
}

1 个答案:

答案 0 :(得分:0)

RestTemplate中找不到

BeanFactory bean,因为您没有配置。

您必须在配置文件中定义如下所示的bean。

@Configuration
public class Config {

   @Bean
   public RestTemplate restTemplate() {
      return new RestTemplate();
   }

}