POST request to Google Apps script from Spring Boot controller

50 Views Asked by At

I am trying to do a post request to google apps script function through a spring boot application and I am getting unauthorized exception.

My spring Boot controller function is as below

@PostMapping("/sendInfo/{id}")
    public void sendInfoToGoogleAppsScript() {

        Object object= objectService.findObjectById(id).get();

        String scriptUrl = "https://script.google.com/a/macros/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/exec";

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> objectHttpEntity = new HttpEntity<>(object);

       restTemplate.exchange(
                scriptUrl,
                HttpMethod.POST,
                objectHttpEntity ,
                String.class
        );

        System.out.println("Data successfully sent to Apps script");

    }

My apps script function is as below

function doPost(e) {
  return ContentService.createTextOutput("Hello World.");
}

The error is as below:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: [no body]] with root cause

org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: [no body]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:106) ~[spring-web-6.1.2.jar:6.1.2]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:183) ~[spring-web-6.1.2.jar:6.1.2]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:137) ~[spring-web-6.1.2.jar:6.1.2]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-6.1.2.jar:6.1.2]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:932) ~[spring-web-6.1.2.jar:6.1.2]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:881) ~[spring-web-6.1.2.jar:6.1.2]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:781) ~[spring-web-6.1.2.jar:6.1.2]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:663) ~[spring-web-6.1.2.jar:6.1.2]

-> Tried deploying the script as web app -> Set executable as User accessing the web -> Set who has access to anyone within my organization (as I dont have any other options except only myself) -> Also tried other combinations for above mentioned, but still the issue persists.

Can anyone suggest answers to this problem or suggest any alternatives(except using Apps script API)?

0

There are 0 best solutions below