我正在尝试在 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/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为