我有一个android应用程序,显示一个特定用户的twitter响应。自从升级到api的1.1版以来,我一直试图让oauth2应用程序只进行身份验证,但是当我发送使用者密钥和机密时,我得到了错误400响应。
代码如下-任何帮助将不胜感激。
HttpClient httpclient = new DefaultHttpClient();
uriString = "https://api.twitter.com/oauth2/token";
HttpPost httppost = new HttpPost(uriString);
HttpParams httpParams = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 15000);
String base64EncodedString =null;
try {
String encodedConsumerKey = URLEncoder.encode("twitter_consumer_key","UTF-8");
String encodedConsumerSecret = URLEncoder.encode("twitter_consumer_secret","UTF-8");
String authString = encodedConsumerKey +":"+encodedConsumerSecret;
base64EncodedString = Base64.encodeToString(authString.getBytes("UTF-8"), Base64.DEFAULT);
} catch (Exception ex) {
//do nothing for now...
}
httppost.setHeader(AUTHORIZATION, "Basic " + base64EncodedString);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response =null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("grant_type", "client_credentials"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
response = httpclient.execute(httppost);
statusCode = response.getStatusLine().getStatusCode();
最佳答案
看起来问题是将字符串编码为base64-我需要base64。不换行而不是base64。默认情况下,这是将字符串抛出两行。
HttpClient httpclient = new DefaultHttpClient();
uriString = "https://api.twitter.com/oauth2/token";
HttpPost httppost = new HttpPost(uriString);
HttpParams httpParams = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 15000);
String base64EncodedString =null;
try {
String encodedConsumerKey = URLEncoder.encode("twitter_consumer_key","UTF-8");
String encodedConsumerSecret = URLEncoder.encode("twitter_consumer_secret","UTF-8");
String authString = encodedConsumerKey +":"+encodedConsumerSecret;
base64EncodedString = Base64.encodeToString(authString.getBytes("UTF-8"), Base64.NO_WRAP); //Changed here!!!
} catch (Exception ex) {
//do nothing for now...
}
httppost.setHeader(AUTHORIZATION, "Basic " + base64EncodedString);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response =null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("grant_type", "client_credentials"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
response = httpclient.execute(httppost);
statusCode = response.getStatusLine().getStatusCode();