【发布时间】:2017-03-11 18:55:51
【问题描述】:
我尝试从 android 应用程序连接我的 spring rest 服务。我的代码不起作用。我从以下教程中学习: http://websystique.com/spring-security/secure-spring-rest-api-using-oauth2/
我试图做到这一点:
“在 /oauth/token 上使用 HTTP POST 请求令牌[访问+刷新],grant_type=password,资源所有者凭据作为 req-params。此外,在授权标头中发送客户端凭据。 发布http://localhost:8080/SpringSecurityOAuth2Example/oauth/token?grant_type=password&username=bill&password=abc123"
我尝试用另一种方式来做,不像教程中那样,而是使用 HttpURLConnection。应该如何查看参数以提出适当的请求? 我在我的手机上模拟它,它通过wifi连接到本地网络。
try {
String plainClientCredentials="my-trusted-client:secret";
String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));
URL urlObj = new URL("http://192.168.1.150:8080/Web_Maxim_Manager/oauth/token");
HttpURLConnection urlConn = (HttpURLConnection) urlObj.openConnection();
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("grant_type", "password");
urlConn.setRequestProperty("username", "bill");
urlConn.setRequestProperty("password", "abc123");
urlConn.setRequestProperty("Authorization", "Basic "+base64ClientCredentials);
urlConn.connect();
String response = urlConn.getResponseMessage();
userName.setText(response);
} catch (Exception e) {
userName.setText("uuuu");
e.printStackTrace();
}
W/System.err: java.net.SocketException: socket failed: EACCES (Permission denied)
W/System.err: at libcore.io.IoBridge.socket(IoBridge.java:623)
W/System.err: at java.net.PlainSocketImpl.create(PlainSocketImpl.java:198)
W/System.err: at java.net.Socket.checkOpenAndCreate(Socket.java:687)
W/System.err: at java.net.Socket.setSoTimeout(Socket.java:541)
W/System.err: at com.android.okhttp.Connection.connect(Connection.java:1179)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:392)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:295)
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
W/System.err: at runwithme.android.maxim.com.myapplication.activities.MainActivity.onCreate(MainActivity.java:43)
我用邮递员应用程序测试了服务,它可以工作。所以,问题出在我的安卓应用上。
【问题讨论】:
标签: java android spring http oauth2