Get access_token from an API with OAuth 2.0 from Android

3

Good morning. I come with a doubt, it turns out that my application has to communicate with a WS to obtain the access_token and thus be able to use the methods of this. The WS uses OAuth 2.0 and the administrator passed the queries to the WS in cURL. I tried to do it from PostMan but I got a long error and from the Windows console if it works well for me. The cURL to obtain the access_token is the following:

curl -X POST -vu <client_id>:<client_secret> http://<ip ws>:8080/oauth/token -H "Accept: application/json" -d "password=<password>&username=<user>&grant_type=password&scope=read%20write&client_secret=<client_secret>&client_id=<client_id>"

This code from Windows console works perfectly, it returns the access_token. Look question is how I make this query from my Android application? Try HttpURLConnect but I have not worked. I need help! Thank you very much.

    
asked by Lean Vitale 20.08.2016 в 01:41
source

1 answer

1

It is suggested to use HttpURLConnection , Apache classes are obsolete

This is an example:

URL url = new URL("http://<ip ws>:8080/oauth/token");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000); //10 segundos timeout
conn.setConnectTimeout(10000); //10 segundos timeout
conn.setRequestMethod("POST"); //Define método POST.
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("password", <password>));
params.add(new BasicNameValuePair("username", <username>));
params.add(new BasicNameValuePair("grant_type", <grant_type>));
params.add(new BasicNameValuePair("scope", <scope>));
params.add(new BasicNameValuePair("client_secret", <client_secret>));
params.add(new BasicNameValuePair("client_id", <client_id>));

OutputStream os = conn.getOutputStream();
BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bwriter.write(getQuery(params));
bwriter.flush();
bwriter.close();
os.close();
conn.connect();
    
answered by 20.08.2016 в 01:57