I'm trying to call the Shopify Partner API to validate the authentication. I have tried multiple ways that were successful, for instance, I received a successful response with Postman:
curl --location --request POST 'https://partners.shopify.com/2XXXXX8/api/2021-10/graphql.json' \
--header 'X-Shopify-Access-Token: prtapi_...' \
--header 'Cookie: _partners_session=a4a...; monorail_user_token=3648077d-...'
I received a successful response when I used org.apache.http.impl.client.CloseableHttpClient;:
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(restUrl);
httpPost.addHeader("X-Shopify-Access-Token", accessToken);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 200) {
log.warn("Auth Failed, Response Status:: " + statusCode);
}
}
}
and I also received a successful response when I used okhttp3.OkHttpClient;
RequestBody reqbody = RequestBody.create(null, new byte[0]);
OkHttpClient client = new OkHttpClient();
Request request =
new Request.Builder()
.url(restUrl)
.addHeader("X-Shopify-Access-Token", accessToken)
.post(reqbody)
.build();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
But the problem is that I am bound to use only org.springframework.web.client.RestTemplate; I have tried multiple ways to achieve that but for some reason, it's not working:
HttpHeaders headers = new HttpHeaders();
headers.set("X-Shopify-Access-Token", accessToken);
headers.add("X-Shopify-Access-Token", accessToken); // Just in case
RequestEntity requestEntity = new RequestEntity(headers, HttpMethod.POST, URI);
ResponseEntity<String> res = restTemplate.exchange(requestEntity, String.class); // Fails
MediaType mediaType = MediaType.TEXT_PLAIN;
RequestEntity requestEntity = RequestEntity.post(uri).headers(headers).contentType(mediaType).build();
ResponseEntity<String> res = restTemplate.exchange(requestEntity, String.class); // Fails
headers.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<String> entity = new HttpEntity<>("", headers);
String res = restTemplate.postForObject(uri, entity, String.class); // Fails
For all the requests above, I'm getting 400 : [Bad Request]. What am I missing? I am also adding Postman's OKHttp version for reference:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
.url("https://partners.shopify.com/2XXXXX8/api/2021-10/graphql.json")
.method("POST", body)
.addHeader("X-Shopify-Access-Token", "prtapi_...")
.addHeader("Cookie", "_partners_session=a4a...; monorail_user_token=3648077d-...")
.build();
Response response = client.newCall(request).execute();