- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试在 Android 应用程序中从 Instagram 获取用户数据,因为我需要获取用户照片并在图库中显示,但我在获取用户数据时遇到了问题。
代码如下:
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() + "/media/recent/?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());
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();
}
但在这部分是要 catch 。
String response = streamToString(urlConnection.getInputStream());
而且我尝试了很多方法来做 JSON 解析,但是在尝试连接到 url 时总是报错,喜欢它:
HttpResponse httpResponse = httpClient.execute(httpPost);
记录的 url 是:
错误是:
11-29 14:31:45.300: W/System.err(11916): java.io.FileNotFoundException: https://api.instagram.com/v1/users/699022341/?access_token=699022341.aef690f.1888e66fed5d4764aeae1c121faa14fb
11-29 14:31:45.300: W/System.err(11916): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
11-29 14:31:45.300: W/System.err(11916): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
我做错了什么或需要 Instagram 许可,或类似的东西?
最佳答案
我在 Instagram 用户身份验证过程中使用了以下代码,这里分享我的代码。希望对你有所帮助,
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");
String userImage = jsonObj.getJSONObject("user").getString(
"profile_picture");
mSession.storeAccessToken(mAccessToken, id, user, name,
userImage);
} 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);
} 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) {
mProgress.dismiss();
mListener.onSuccess();
// fetchUserName();
} else {
// mProgress.dismiss();
// mListener.onSuccess();
}
}
};
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void setListener(OAuthAuthenticationListener listener) {
mListener = listener;
}
// getting username
public String getUserName() {
return mSession.getUsername();
}
// getting user id
public String getId() {
return mSession.getId();
}
// getting username
public String getName() {
return mSession.getName();
}
// getting user image
public String getUserPicture() {
return mSession.getUserImage();
}
// getting accesstoken
public String getAccessToken() {
return mSession.getAccessToken();
}
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);
}
}
InstagramDialog.java
package br.com.dina.oauth.instagram;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Display 37Signals authentication dialog.
*
* @author Thiago Locatelli <thiago.locatelli@gmail.com>
* @author Lorensius W. L T <lorenz@londatiga.net>
*
*/
public class InstagramDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = { 460, 260 };
static final float[] DIMENSIONS_PORTRAIT = { 420, 420 };
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private OAuthDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Instagram-WebView";
public InstagramDialog(Context context, String url,
OAuthDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT
: DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams(
(int) (dimensions[0] * scale + 0.5f), (int) (dimensions[1]
* scale + 0.5f)));
CookieSyncManager.createInstance(getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
mTitle = new TextView(getContext());
mTitle.setText("Instagram");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(Color.BLACK);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new OAuthWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class OAuthWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(InstagramApp.mCallbackUrl)) {
String urls[] = url.split("=");
mListener.onComplete(urls[1]);
InstagramDialog.this.dismiss();
return true;
}
return false;
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
InstagramDialog.this.dismiss();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
Log.d(TAG, "onPageFinished URL: " + url);
mSpinner.dismiss();
}
}
public interface OAuthDialogListener {
public abstract void onComplete(String accessToken);
public abstract void onError(String error);
}
}
InstagramSession.java
package br.com.dina.oauth.instagram;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* Manage access token and user name. Uses shared preferences to store access
* token and user name.
*
* @author Thiago Locatelli <thiago.locatelli@gmail.com>
* @author Lorensius W. L T <lorenz@londatiga.net>
*
*/
public class InstagramSession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String SHARED = "Instagram_Preferences";
private static final String API_USERNAME = "username";
private static final String API_ID = "id";
private static final String API_NAME = "name";
private static final String API_ACCESS_TOKEN = "access_token";
private static final String API_USER_IMAGE = "user_image";
public InstagramSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
/**
*
* @param accessToken
* @param expireToken
* @param expiresIn
* @param username
*/
public void storeAccessToken(String accessToken, String id,
String username, String name, String image) {
editor.putString(API_ID, id);
editor.putString(API_NAME, name);
editor.putString(API_ACCESS_TOKEN, accessToken);
editor.putString(API_USERNAME, username);
editor.putString(API_USER_IMAGE, image);
editor.commit();
}
public void storeAccessToken(String accessToken) {
editor.putString(API_ACCESS_TOKEN, accessToken);
editor.commit();
}
/**
* Reset access token and user name
*/
public void resetAccessToken() {
editor.putString(API_ID, null);
editor.putString(API_NAME, null);
editor.putString(API_ACCESS_TOKEN, null);
editor.putString(API_USERNAME, null);
editor.putString(API_USER_IMAGE, null);
editor.commit();
}
/**
* Get user name
*
* @return User name
*/
public String getUsername() {
return sharedPref.getString(API_USERNAME, null);
}
/**
*
* @return
*/
public String getId() {
return sharedPref.getString(API_ID, null);
}
/**
*
* @return
*/
public String getName() {
return sharedPref.getString(API_NAME, null);
}
/**
* Get access token
*
* @return Access token
*/
public String getAccessToken() {
return sharedPref.getString(API_ACCESS_TOKEN, null);
}
/**
* Get userImage
*
* @return userImage
*/
public String getUserImage() {
return sharedPref.getString(API_USER_IMAGE, null);
}
}
以上三个类是静态的,我要感谢作者,在 InstagramApp.java 类中我稍微修改了 getter setter 方法以获取所有用户值,在 MainActivity.java 中我使用了以下代码。
private InstagramApp instaObj;
public static final String CLIENT_ID = "Your_ID";
public static final String CLIENT_SECRET = "Your_Sec_Key";
public static final String CALLBACK_URL = "Your_call_back_URL";
// Instagram Implementation
instaObj = new InstagramApp(this, CLIENT_ID,
CLIENT_SECRET, CALLBACK_URL);
instaObj.setListener(listener);
instaObj.authorize(); //add this in your button click or wherever you need to call the instagram api
OAuthAuthenticationListener listener = new OAuthAuthenticationListener() {
@Override
public void onSuccess() {
Log.e("Userid", instaObj.getId());
Log.e("Name", instaObj.getName());
Log.e("UserName", instaObj.getUserName());
}
@Override
public void onFail(String error) {
Toast.makeText(LoginPageActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
};
关于android - 如何从 Android 用户获取 Instagram 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20290309/
我最近在/ drawable中添加了一些.gifs,以便可以将它们与按钮一起使用。这个工作正常(没有错误)。现在,当我重建/运行我的应用程序时,出现以下错误: Error: Gradle: Execu
Android 中有返回内部存储数据路径的方法吗? 我有 2 部 Android 智能手机(Samsung s2 和 s7 edge),我在其中安装了一个应用程序。我想使用位于这条路径中的 sqlit
这个问题在这里已经有了答案: What's the difference between "?android:" and "@android:" in an android layout xml f
我只想知道 android 开发手机、android 普通手机和 android root 手机之间的实际区别。 我们不能从实体店或除 android marketplace 以外的其他地方购买开发手
自Gradle更新以来,我正在努力使这个项目达到标准。这是一个团队项目,它使用的是android-apt插件。我已经进行了必要的语法更改(编译->实现和apt->注释处理器),但是编译器仍在告诉我存在
我是android和kotlin的新手,所以请原谅要解决的一个非常简单的问题! 我已经使用导航体系结构组件创建了一个基本应用程序,使用了底部的导航栏和三个导航选项。每个导航选项都指向一个专用片段,该片
我目前正在使用 Facebook official SDK for Android . 我现在正在使用高级示例应用程序,但我不知道如何让它获取应用程序墙/流/状态而不是登录的用户。 这可能吗?在那种情
我在下载文件时遇到问题, 我可以在模拟器中下载文件,但无法在手机上使用。我已经定义了上网和写入 SD 卡的权限。 我在服务器上有一个 doc 文件,如果用户单击下载。它下载文件。这在模拟器中工作正常但
这个问题在这里已经有了答案: What is the difference between gravity and layout_gravity in Android? (22 个答案) 关闭 9
任何人都可以告诉我什么是 android 缓存和应用程序缓存,因为当我们谈论缓存清理应用程序时,它的作用是,缓存清理概念是清理应用程序缓存还是像内存管理一样主存储、RAM、缓存是不同的并且据我所知,缓
假设应用程序 Foo 和 Eggs 在同一台 Android 设备上。任一应用程序都可以获取设备上所有应用程序的列表。一个应用程序是否有可能知道另一个应用程序是否已经运行以及运行了多长时间? 最佳答案
我有点困惑,我只看到了从 android 到 pc 或者从 android 到 pc 的例子。我需要制作一个从两部手机 (android) 连接的 android 应用程序进行视频聊天。我在想,我知道
用于使用 Android 以编程方式锁定屏幕。我从 Stackoverflow 之前关于此的问题中得到了一些好主意,并且我做得很好,但是当我运行该代码时,没有异常和错误。而且,屏幕没有锁定。请在这段代
文档说: android:layout_alignParentStart If true, makes the start edge of this view match the start edge
我不知道这两个属性和高度之间的区别。 以一个TextView为例,如果我将它的layout_width设置为wrap_content,并将它的width设置为50 dip,会发生什么情况? 最佳答案
这两个属性有什么关系?如果我有 android:noHistory="true",那么有 android:finishOnTaskLaunch="true" 有什么意义吗? 最佳答案 假设您的应用中有
我是新手,正在尝试理解以下 XML 代码: 查看 developer.android.com 上的文档,它说“starStyle”是 R.attr 中的常量, public static final
在下面的代码中,为什么当我设置时单选按钮的外观会发生变化 android:layout_width="fill_parent" 和 android:width="fill_parent" 我说的是
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 9
假设我有一个函数 fun myFunction(name:String, email:String){},当我调用这个函数时 myFunction('Ali', 'ali@test.com ') 如何
我是一名优秀的程序员,十分优秀!