Получение Oauth токена

Добрый день.

Пытаюсь вызвать запрос на получение Oauth токена:

 private String getauthToken () throws IOException, JSONException {
    	 String authToken = null;
    	 URL url = new URL (Constants.auuthURLString);
    	 this.authConnection = (HttpURLConnection) url.openConnection();
    	
    	 String authenc =  new String(Base64.encode(Constants.authClient.getBytes()));
    	 
    	 this.authConnection.setRequestProperty("Authorization", "Basic "+authenc);
    	 this.authConnection.setRequestProperty("Content-Type",Constants.authContentType);
    	 this.authConnection.setRequestProperty("Accept-Charset", "UTF-8");
    	 this.authConnection.setRequestMethod("POST");
    	 this.authConnection.setDoOutput(true);
    	 OutputStream os = this.authConnection.getOutputStream();
         os.write(Constants.authPostParmas.getBytes());
         os.flush();
         os.close();
         
    	// this.authConnection.setConnectTimeout(9000);
    	 
         this.authConnection.connect();
         System.out.println("Подключились и  ждем ответа"+this.authConnection.toString());
         int respCode = this.authConnection.getResponseCode();
         
         
         System.out.println("respCode"  +respCode);
         if (respCode ==200) {
        	 System.out.println("Запрос на получение ключа авторизации отработал");
        	 
        	 String responseJson = "";
        	   String inputLine;
        	   BufferedReader in = new BufferedReader(new InputStreamReader((this.authConnection.
        			   getInputStream()),"UTF-8"));
               while ((inputLine = in.readLine()) != null) 
            	   responseJson += inputLine;
                in.close();
        	 System.out.println("responseJson" + responseJson);
                JSONObject jsonObject = new JSONObject(responseJson);
                
                if (jsonObject.has("access_token")) {
                	authToken = jsonObject.getString("access_token");
                	System.out.println("Authorization Token = "+authToken);
                };
         } else {
        	 System.out.println("Сервис авторизации вернул код: "+respCode);
         }
         
    	return authToken;
}

Класс Constants:

public class Constants {
	
	public static final String auuthURLString = "http://localhost:8080/bankref/rest/v2/oauth/token";
	public static final String serviceURLString = 
		//"http://localhost:8080/bankref/rest/v2/services/bankref_EmployeeService/createNewEmployee";
		"http://localhost:8080/bankref/rest/myapi/createNewEmployee";
	public static final String serviceURLStringObj = 
		"http://localhost:8080/bankref/rest/myapi/createNewEmployeeObj";
	public static final String authPostParmas = "grant_type=password&username=admin&password=admin";
	public static final String authClient = "client:secret";
	public static final String authContentType = "application/x-www-form-urlencoded";
	
}

В результате : высвечивается ошибка:

java.lang.NullPointerException

на строке:

 int respCode = this.authConnection.getResponseCode();

Также в логах Tomkat заметил, что почему-то подключение идет 2 раза:

22:10:09.386 INFO  c.h.c.s.a.AuthenticationManagerBean - Logged in: 5bc47df7-ee52-a5f4-0126-b921950165d1 [admin]
22:10:09.396 INFO  c.h.r.auth.ClientProxyTokenStore - REST API access token stored: [admin] ***-f1cdb5eef0ab
22:10:09.511 INFO  c.h.c.s.a.AuthenticationManagerBean - Logged in: b2e3fbcb-f41b-19b1-d711-d6dd3a8eeaa8 [admin]
22:10:09.521 INFO  c.h.r.auth.ClientProxyTokenStore - REST API access token stored: [admin] ***-f68eb353bace

Самое интересное, что вчера этот функционал работал.

Подскажите пожалуйста, в чем может быть проблема.

Заранее спасибо.

Здравствуйте,

По всей вероятности, в вашем коде есть ошибка.

Для работы с REST-API из Java я рекомендую вам воспользоваться библиотекой masquerade-connector: https://github.com/cuba-platform/masquerade

Достаточно подключить Gradle зависимость:

com.haulmont.masquerade:masquerade-connector:1.0.6

Пример использования:

UserService userService = Connectors.restApi(UserService.class);
List<User> allUsers = userService.all().execute().body();

Полный код примера: https://github.com/cuba-platform/masquerade/blob/master/modules/connector/src/test/java/com/haulmont/masquerade/RestApiTest.java

Библиотека использует в качестве транспорта retrofit2.