嗨,谢谢你的帮助。
从我的Android App我尝试获得PayPal Oauth refresh_token。
卷曲代码是:
curl 'https://api.paypal.com/v1/oauth2/token' \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Authorization: Basic QWZV...==" \
-d 'grant_type=authorization_code&response_type=token&redirect_uri=urn:ietf:wg:oauth:2.0:oob&code=EBYhRW3ncivudQn8UopLp4A28...'
我喜欢这个。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.sandbox.paypal.com/v1/oauth2/token");
try {
String text=CONFIG_CLIENT_ID+":"+SECRET;
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
httppost.addHeader("content-type", "application/x-www-form-urlencoded");
httppost.addHeader("Authorization", "Basic "+base64);
StringEntity se=new StringEntity("grant_type=authorization_code&response_type=token&redirect_uri=urn:ietf:wg:oauth:2.0:oob&code="+authorization.getAuthorizationCode());
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
但我收到以下回复:
无效网址
请求的网址" / v1 / oauth2 / token",无效。
编辑编辑编辑编辑编辑编辑
如果我使用
HttpPost httppost = new HttpPost("https://api.sandbox.paypal.com")
我明白了:
无效网址
请求的网址" /",无效。
参考编号#9.8c5e6cc1.1395837240.16f01684
编辑编辑编辑编辑编辑编辑
以下代码似乎正在运作,
感谢Sabuj Hassan的回答。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.sandbox.paypal.com/v1/oauth2/token");
try {
String text=CONFIG_CLIENT_ID+":"+SECRET;
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
httppost.addHeader("content-type", "application/x-www-form-urlencoded");
httppost.addHeader("Authorization", "Basic "+base64);
StringEntity se=new StringEntity("grant_type=authorization_code&response_type=token&redirect_uri=urn:ietf:wg:oauth:2.0:oob&code="+authorization.getAuthorizationCode());
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
但现在我从PayPal沙盒服务器得到以下响应:
{"error":"invalid_request","error_description":"Invalid auth code"}
答案 0 :(得分:2)
我的代码似乎没问题。它可以很好地将数据发送到我的托管服务器。所以我怀疑问题出在你的下一行:
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
打印base64
,看看它与curl命令的标题是否完全匹配。我想相信它的不同。可能它添加了换行符(在base64中)。
所以使用这个:
String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
请参阅其他encoding flags的文档。