我正在尝试使用 twitter4j 库创建一个 Twitter 客户端。但是我仍然不清楚这些东西,也找不到好的教程。大多数教程都已过时。我主要想知道,在创建 Twitter 客户端时是否必须每次都使用 OAuth?如果不是,我应该怎么做(我的意思是,没有获得“消费者 key ”和“消费者 secret ”,只需输入用户名和密码)?任何帮助,将不胜感激。谢谢。
最佳答案
您必须在 http://dev.twitter.com/apps/ 注册一个应用程序如果你想使用 twitter4j,获取消费者 key 和 secret 。
我的应用程序只是发布一 strip 有图像的推文,我希望找到一个简单的推文功能,但却发现了一大堆身份验证细节和代码线程问题。
为了更轻松地使用图像发送推文,我将 twitter4j 封装在一个包装器 JAR 文件中,该文件处理所有身份验证和线程问题。它只需要几行代码(至少 3 行)即可工作。 JAR 文件名为 MSTwitter.jar .
MSTwitter.jar 包含三个文件,其中一个是 MSTwitter。此文件的顶部是解释如何使用 JAR 的注释。它们在这里重复:
To use MSTwitter.jar:
-Project setup:
-Create a twitter app on https://dev.twitter.com/apps/ to get:
-CONSUMER_KEY a public key(string) used to authenticate your app with Twitter.com
-CONSUMER_SECRET a private key(string) used to authenticate your app with Twitter.com
You don't need any thing else so authorization url etc are not important for this process
-Put twitter4j-core-3.0.2.jar and MSTwitter.jar files in your project's libs directory:
-You can download twitter4j from from http://twitter4j.org
-Register the jars in your project build path:
Project->Properties->Java Build Path->Libraries->Add Jar
->select the jar files you just added to your project's libs directory.
-Make AndroidManifest.xml modifications
-Add <uses-permission android:name="android.permission.INTERNET" /> inside manifest section (<manifest>here</manifest>)
-Add <uses-permission android:name="com.mindspiker.mstwitter.MSTwitterService" /> inside manifest section
-Add <uses-permission android:name="android.permission.BROADCAST_STICKY" /> inside manifest section
-Add <activity android:name="com.mindspiker.mstwitter.MSTwitterAuthorizer" /> inside application section.
-Add <service android:name="com.mindspiker.mstwitter.MSTwitterService" /> inside application section.
-Code to add to you calling activity
-Define a module MSTwitter variable.
-In onCreate() allocate a module level MSTwitter variable
ex: mMTwitter = new MSTWitter(args);]
-Add code to catch response from MSTwitterAuthorizer in your activity's onActivityResult()
ex:@Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ mMSTwitter.onCallingActivityResult(requestCode, resultCode, data); }
-Call startTweet(String text, String imagePath) on your MSTwitter object instance.
if you image is held in memory and not saved to disk call
MSTwitter.putBitmapInDiskCache() to save to a temporary file on disk.
-(Optional) Add a MSTwitterResultReceiver to catch MSTwitter events which are
fired at various stages of the process.
MSTwitterResultReceiver events:
-MSTWEET_STATUS_AUTHORIZING the app is not authorized and the authorization process is starting.
-MSTWEET_STATUS_STARTING the app is authorized and sending the tweet text and image is starting.
-MSTWEET_STATUS_FINSIHED_SUCCCESS the tweet is done and was successful.
-MSTWEET_STATUS_FINSIHED_FAILED the tweet is done and failed to complete.
Notes:
-If your project compiles but crashes when any twwiter4j object is instantiated a possible cause may be trying to add the jars as external jars instead of the suggested method above. If your libraries directory already exists but is called 'lib', change the name to 'libs'. Sounds crazy I know, but works in some situations.
-To prevent large images from being passed around between intents images should be cached to disk and retrieved when used. Only the file name is passed between intents.
-To perform tasks on a separate thread that passes information to and from activities, which could be destroyed at any time (phone call, screen orientation change, etc.), a method using intent services to perform the work and sticky broadcasts to pass the data was employed. For more on this method and why it was used check out: http://stackoverflow.com/questions/1111980/how-to-handle-screen-orientation-change-when-progress-dialog-and-background-thre/8074278#8074278
以下文件来自发布带有图片的推文的示例项目。
androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.imagetweettester" android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.mindspiker.mstwitter.MSTwitterService" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
<activity android:name="com.example.imagetweettester.MainActivity" android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.mindspiker.mstwitter.MSTwitterAuthorizer" />
<service android:name="com.mindspiker.mstwitter.MSTwitterService" />
</application>
</manifest>
主 Activity .java
package com.example.imagetweettester;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.mindspiker.mstwitter.MSTwitter;
import com.mindspiker.mstwitter.MSTwitter.MSTwitterResultReceiver;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Consumer Key generated when you registered your app at https://dev.twitter.com/apps/ */
public static final String CONSUMER_KEY = "yourConsumerKeyHere";
/** Consumer Secret generated when you registered your app at https://dev.twitter.com/apps/ */
public static final String CONSUMER_SECRET = "yourConsumerSecretHere";
/** module level variables used in different parts of this module */
private MSTwitter mMSTwitter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setup button to call local tweet() function
Button tweetButton = (Button) findViewById(R.id.button1);
tweetButton.setOnClickListener(new OnClickListener () {
@Override
public void onClick(View v) {
tweet();
}
});
// make a MSTwitter event handler to receive tweet send events
MSTwitterResultReceiver myMSTReceiver = new MSTwitterResultReceiver() {
@Override
public void onRecieve(int tweetLifeCycleEvent, String tweetMessage) {
handleTweetMessage(tweetLifeCycleEvent, tweetMessage);
}
};
// create module level MSTwitter object.
// This object can be destroyed and recreated without interrupting the send tweet process.
// So no need to save and pass back in savedInstanceState bundle.
mMSTwitter = new MSTwitter(this, CONSUMER_KEY, CONSUMER_SECRET, myMSTReceiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//This MUST MUST be done for authorization to work. If your get a MSTWEET_STATUS_AUTHORIZING
// message and nothing else it is most likely because this is not being done.
mMSTwitter.onCallingActivityResult(requestCode, resultCode, data);
}
/**
* Send tweet using MSTwitter object created in onCreate()
*/
private void tweet() {
// assemble data
// get text from layout control
EditText tweetEditText = (EditText) findViewById(R.id.editText1);
String textToTweet = tweetEditText.getText().toString();
// get image from resource
Bitmap imageToTweet = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// use MSTwitter function to save image to file because startTweet() takes an image path
// this is done to avoid passing large image files between intents which is not android best practices
String tweetImagePath = MSTwitter.putBitmapInDiskCache(this, imageToTweet);
// start the tweet
mMSTwitter.startTweet(textToTweet, tweetImagePath);
}
@SuppressLint("SimpleDateFormat")
private void handleTweetMessage(int event, String message) {
String note = "";
switch (event) {
case MSTwitter.MSTWEET_STATUS_AUTHORIZING:
note = "Authorizing app with twitter.com";
break;
case MSTwitter.MSTWEET_STATUS_STARTING:
note = "Tweet data send started";
break;
case MSTwitter.MSTWEET_STATUS_FINSIHED_SUCCCESS:
note = "Tweet sent successfully";
break;
case MSTwitter.MSTWEET_STATUS_FINSIHED_FAILED:
note = "Tweet failed:" + message;
break;
}
// add note to results TextView
SimpleDateFormat timeFmt = new SimpleDateFormat("h:mm:ss.S");
String timeS = timeFmt.format(new Date());
TextView resultsTV = (TextView) findViewById(R.id.resultsTextView);
resultsTV.setText(resultsTV.getText() + "\n[Message received at " + timeS +"]\n" + note);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" tools:context=".MainActivity" >
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Start Tweet" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text to tweet:" />
<EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:text="Test tweet text" >
<requestFocus />
</EditText>
<ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Results:" />
<TextView android:id="@+id/resultsTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" />
</LinearLayout>
关于android - 使用适用于 Android 的 Twitter4j 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665616/
我正在学习如何使用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程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje