Android 尝试获取Instagram API的访问令牌时发生FileNotFoundException
尝试检索访问令牌时,我收到一个Android 尝试获取Instagram API的访问令牌时发生FileNotFoundException,android,instagram,Android,Instagram,尝试检索访问令牌时,我收到一个FileNotFoundException: java.io.FileNotFoundException: https://api.instagram.com/oauth/access_token&client_id=e909da82f8544a70bb9b29434xxxxxx&client_secret=fa34037e0f534628bb9becd1a3xxxxxx&grant_type=authorization_code&r
FileNotFoundException
:
java.io.FileNotFoundException: https://api.instagram.com/oauth/access_token&client_id=e909da82f8544a70bb9b29434xxxxxx&client_secret=fa34037e0f534628bb9becd1a3xxxxxx&grant_type=authorization_code&redirect_uri=x-oauthflow-instagram://callback&code=520401255.e909da8.244c14ba79e842868a695192835c83ac
01-01 11:50:39.371: W/System.err(21868): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
错误发生在这一行
JSONObject jsonObj = (JSONObject) new JSONTokener(streamToString(urlConnection.getInputStream())).nextValue();
我做错了什么?只需将InstagramApp.java替换为库中当前的类即可
package br.com.dina.oauth.instagram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import br.com.dina.oauth.instagram.InstagramDialog.OAuthDialogListener;
/**
*
* @author Thiago Locatelli <thiago.locatelli@gmail.com>
* @author Lorensius W. L T <lorenz@londatiga.net>
*
*/
public class InstagramApp {
private InstagramSession mSession;
private InstagramDialog mDialog;
private OAuthAuthenticationListener mListener;
private ProgressDialog mProgress;
private String mAuthUrl;
private String mTokenUrl;
private String mAccessToken;
private Context mCtx;
private String mClientId;
private String mClientSecret;
private static int WHAT_FINALIZE = 0;
private static int WHAT_ERROR = 1;
private static int WHAT_FETCH_INFO = 2;
/**
* Callback url, as set in 'Manage OAuth Costumers' page
* (https://developer.github.com/)
*/
public static String mCallbackUrl = "";
private static final String AUTH_URL = "https://api.instagram.com/oauth/authorize/";
private static final String TOKEN_URL = "https://api.instagram.com/oauth/access_token";
private static final String API_URL = "https://api.instagram.com/v1";
private static final String TAG = "InstagramAPI";
public InstagramApp(Context context, String clientId, String clientSecret,
String callbackUrl) {
mClientId = clientId;
mClientSecret = clientSecret;
mCtx = context;
mSession = new InstagramSession(context);
mAccessToken = mSession.getAccessToken();
mCallbackUrl = callbackUrl;
mTokenUrl = TOKEN_URL + "?client_id=" + clientId + "&client_secret="
+ clientSecret + "&redirect_uri=" + mCallbackUrl + "&grant_type=authorization_code";
mAuthUrl = AUTH_URL + "?client_id=" + clientId + "&redirect_uri="
+ mCallbackUrl + "&response_type=code&display=touch&scope=likes+comments+relationships";
OAuthDialogListener listener = new OAuthDialogListener() {
@Override
public void onComplete(String code) {
getAccessToken(code);
}
@Override
public void onError(String error) {
mListener.onFail("Authorization failed");
}
};
mDialog = new InstagramDialog(context, mAuthUrl, listener);
mProgress = new ProgressDialog(context);
mProgress.setCancelable(false);
}
private void getAccessToken(final String code) {
mProgress.setMessage("Getting access token ...");
mProgress.show();
new Thread() {
@Override
public void run() {
Log.i(TAG, "Getting access token");
int what = WHAT_FETCH_INFO;
try {
URL url = new URL(TOKEN_URL);
//URL url = new URL(mTokenUrl + "&code=" + code);
Log.i(TAG, "Opening Token URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//urlConnection.connect();
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write("client_id="+mClientId+
"&client_secret="+mClientSecret+
"&grant_type=authorization_code" +
"&redirect_uri="+mCallbackUrl+
"&code=" + code);
writer.flush();
String response = streamToString(urlConnection.getInputStream());
Log.i(TAG, "response " + response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
mAccessToken = jsonObj.getString("access_token");
Log.i(TAG, "Got access token: " + mAccessToken);
String id = jsonObj.getJSONObject("user").getString("id");
String user = jsonObj.getJSONObject("user").getString("username");
String name = jsonObj.getJSONObject("user").getString("full_name");
mSession.storeAccessToken(mAccessToken, id, user, name);
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0));
}
}.start();
}
private void fetchUserName() {
mProgress.setMessage("Finalizing ...");
new Thread() {
@Override
public void run() {
Log.i(TAG, "Fetching user info");
int what = WHAT_FINALIZE;
try {
URL url = new URL(API_URL + "/users/" + mSession.getId() + "/?access_token=" + mAccessToken);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio = jsonObj.getJSONObject("data").getString("bio");
Log.i(TAG, "Got name: " + name + ", bio [" + bio + "]");
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == WHAT_ERROR) {
mProgress.dismiss();
if(msg.arg1 == 1) {
mListener.onFail("Failed to get access token");
}
else if(msg.arg1 == 2) {
mListener.onFail("Failed to get user information");
}
}
else if(msg.what == WHAT_FETCH_INFO) {
fetchUserName();
}
else {
mProgress.dismiss();
mListener.onSuccess();
}
}
};
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void setListener(OAuthAuthenticationListener listener) {
mListener = listener;
}
public String getUserName() {
return mSession.getUsername();
}
public String getId() {
return mSession.getId();
}
public String getName() {
return mSession.getName();
}
public void authorize() {
//Intent webAuthIntent = new Intent(Intent.ACTION_VIEW);
//webAuthIntent.setData(Uri.parse(AUTH_URL));
//mCtx.startActivity(webAuthIntent);
mDialog.show();
}
private String streamToString(InputStream is) throws IOException {
String str = "";
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
str = sb.toString();
}
return str;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public interface OAuthAuthenticationListener {
public abstract void onSuccess();
public abstract void onFail(String error);
}
}
package br.com.dina.oauth.instagram;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStreamWriter;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入org.json.JSONObject;
导入org.json.JSONTokener;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.Intent;
导入android.net.Uri;
导入android.os.Handler;
导入android.os.Message;
导入android.util.Log;
导入br.com.dina.oauth.instagram.InstagramDialog.OAuthDialogListener;
/**
*
*@作者蒂亚戈·洛卡特利
*@作者洛伦西斯·W·L·T
*
*/
公共类InstagramApp{
私人InstagramSession;
私人InstagramDialog;
私有OAuthAuthenticationListener mListener;
私人进程;
私人字符串毛瑟尔;
私有字符串mTokenUrl;
私有字符串标记;
私有上下文mCtx;
私有字符串mClientId;
私有字符串mClientSecret;
私有静态int什么_FINALIZE=0;
私有静态int WHAT_ERROR=1;
私有静态int WHAT_FETCH_INFO=2;
/**
*“管理OAuth客户”页面中设置的回调url
* (https://developer.github.com/)
*/
公共静态字符串mCallbackUrl=“”;
私有静态最终字符串AUTH_URL=”https://api.instagram.com/oauth/authorize/";
私有静态最终字符串标记\u URL=”https://api.instagram.com/oauth/access_token";
私有静态最终字符串API_URL=”https://api.instagram.com/v1";
私有静态最终字符串TAG=“InstagramAPI”;
公共InstagramApp(上下文、字符串clientId、字符串clientSecret、,
字符串回调(URL){
mClientId=clientId;
mClientSecret=clientSecret;
mCtx=上下文;
mSession=新InstagramSession(上下文);
MacAccessToken=mSession.getAccessToken();
mCallbackUrl=callbackUrl;
mTokenUrl=令牌\u URL+“?客户端\u id=“+clientId+”&客户端\u机密=”
+clientSecret+“&redirect_uri=“+mCallbackUrl+”&grant_type=authorization_code”;
mAuthUrl=AUTH_URL+“?客户端_id=“+clientId+”&重定向_uri=”
+mCallbackUrl+“&response_type=code&display=touch&scope=likes+comments+relationships”;
OAuthDialogListener=新的OAuthDialogListener(){
@凌驾
公共void onComplete(字符串代码){
getAccessToken(代码);
}
@凌驾
public void onError(字符串错误){
mListener.onFail(“授权失败”);
}
};
mDialog=新InstagramDialog(上下文、Mauthull、侦听器);
mProgress=新建进度对话框(上下文);
可设置可取消的进程(错误);
}
私有void getAccessToken(最终字符串代码){
setMessage(“获取访问令牌…”);
mProgress.show();
新线程(){
@凌驾
公开募捐{
Log.i(标记“获取访问令牌”);
int what=获取什么信息;
试一试{
URL URL=新URL(令牌\ URL);
//URL URL=新URL(mTokenUrl+“&code=“+code”);
Log.i(标记“打开令牌URL”+URL.toString());
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod(“POST”);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//urlConnection.connect();
OutputStreamWriter writer=新的OutputStreamWriter(urlConnection.getOutputStream());
writer.write(“client_id=“+mClientId+
“&client_secret=“+mClientSecret”+
“&授予\类型=授权\代码”+
“&redirect_uri=“+mCallbackUrl”+
“&code=“+code”);
writer.flush();
字符串响应=streamToString(urlConnection.getInputStream());
Log.i(标签,“响应”+响应);
JSONObject JSONObject=(JSONObject)新的JSONTokener(response).nextValue();
mAccessToken=jsonObj.getString(“访问令牌”);
Log.i(标记“获取访问令牌:”+mAccessToken);
String id=jsonObj.getJSONObject(“用户”).getString(“id”);
String user=jsonObj.getJSONObject(“用户”).getString(“用户名”);
String name=jsonObj.getJSONObject(“用户”).getString(“全名”);
mSession.storeAccessToken(MacAccessToken、id、用户、名称);
}捕获(例外情况除外){
什么=什么错误;
例如printStackTrace();
}
mHandler.sendMessage(mHandler.getainmessage(what,1,0));
}
}.start();
}
私有void fetchUserName(){
设置消息(“正在完成…”);
新线程(){
@凌驾
公开募捐{
Log.i(标签,“获取用户信息”);
int what=what\u;
试一试{
URL URL=新URL(API_URL+“/users/”+mSession.getId()+“/?access_token=“+mAccessToken”);
Log.d(标记“打开URL”+URL.toString());
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setR