我一直在尝试将以下 Curl 脚本转换为 Java 以获取访问令牌,但似乎总是以 400 或 401 失败。我做错了什么?curl 到 java 的转换是否在下面正确完成?请指教...
卷曲脚本:
curl -X POST https://developers.crittercism.com/v1.0/token -u WV3v7ZTbYmqtUOMNvO7oPhLi8RN9zFoo -d 'grant_type=password&username=david@crittercism.com&password=riTiBw28%3DpmFu'
其中,“WV3v7ZTbYmqtUOMNvO7oPhLi8RN9zFoo”是 oAuth ClientID。
Java 代码:
String url = "https://developers.crittercism.com/v1.0/token";
String urlParameters = "grant_type=password&username=myemail@email.com&password=secretpass";
String clientId = "nD8FiwFiOB1rpU5HVc2ESyRAwbFOOO:"; //Just for ref
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
//add request header
String basicAuth = new String(Base64.encode(clientId.getBytes()));
con.setRequestProperty ("Authorization", String.format("Basic %s", basicAuth));
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
con.setRequestMethod("POST");
// Send post request
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
被抛出的异常,
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://developers.crittercism.com/v1.0/token
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at CrittercismClient.sendPost(CrittercismClient.java:102)
at CrittercismClient.main(CrittercismClient.java:26)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://developers.crittercism.com/v1.0/token
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at CrittercismClient.sendPost(CrittercismClient.java:96)
... 1 more