Reputation: 41
Please note that I must use java 8 for this work. Initially do a POST for authentication to the middleware Gateway and get accessToken. Using the same access token I do a POST to the service end point url. I set all the required headers in request properties but I get 401 in response. I am trying to not use any external libraries and trying to do this is pure java. Any help appreciated.
Exact error I get is {"error": "invalid_grant", "error_description": "token not found, expired or invalid", .....} As you can see below I am setting access token, is there something else missing in this code? Below is the code:
private static void sendPOST(){
String jsonStr = getPostDataJson();
InputStream stream = null;
BufferedReader reader = null;
HttpURLConnection conn = null;
if(accessToken != null && accessToken.length()>0) {
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", String.valueOf(jsonStr.length()));
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonStr);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
System.out.println("Status Code :" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
stream = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
System.out.println("Post request encountered error." + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}}
Upvotes: 0
Views: 293
Reputation: 41
The issue was resolved, there was an error in accessToken header.
Upvotes: 0