Reputation: 181
I need to get access from java application to some RESTful web service which uses token-based authentication. As I understood the best choice for this purpose is to use JAX-RS-based libraries like Jersey, but I am very new to this matter. Maybe someone could help me by giving example code of proper request to get a token from web service.
What we have:
As I understood, to get a token I have to send POST request along with the following headers:
and the following parameter:
grant_type=password&username=someusername&password=somepassword&scope=profile
Hope somebody will help me with example code.
Upvotes: 1
Views: 14071
Reputation: 181
Resolved!
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public void getHttpCon() throws Exception{
String POST_PARAMS = "grant_type=password&username=someusrname&password=somepswd&scope=profile";
URL obj = new URL("http://someIP/oauth/token");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Authorization",
"Basic Base64_encoded_clientId:clientSecret");
con.setRequestProperty("Accept",
"application/x-www-form-urlencoded");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
Upvotes: 4
Reputation: 1658
Some points:
Upvotes: 0