我需要从java应用程序访问一些使用基于令牌的身份验证的RESTful Web服务。据我所知,为此目的的最佳选择是使用像泽西岛这样的基于JAX-RS的库,但我对这个问题很新。也许有人可以通过提供适当请求的示例代码来帮助我从Web服务获取令牌。
我们拥有什么:
据我所知,要获取令牌,我必须发送POST请求以及以下标题:
和以下参数:
grant_type =密码&安培;用户名= someusername&安培;密码= somepassword&安培;范围=简档
希望有人能帮我提供示例代码。
答案 0 :(得分:0)
有些观点:
答案 1 :(得分:0)
解决!
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");
}
}