gpt4 book ai didi

java - 如何使用自己的应用程序在 Twitter 上发布推文

转载 作者:行者123 更新时间:2023-12-02 06:20:16 25 4
gpt4 key购买 nike

我想在 Twitter 上发布我的应用程序的推文。这条推文将显示在我的应用程序和 Twitter 中。

我拥有该用户的所有详细信息,但我不想登录 Twitter。这是我从网络服务获取的格式:

<string xmlns="http://tempuri.org/">
{"Id":"cc02cf6c-c143-4921-b5d6-6afec1243c10","TwitterUserId":"123456",
"TwitterScreenName":"abc", "OAuthToken":"xxxxxxxxxxxxxxxxxxxx",
"OAuthSecret":"xxxxxxxxxxxx", "UserId":"zzzzzzzzzz", "FollowersCount":1, "IsActive":true,
"FollowingCount":13, "ProfileUrl":"", "ProfileImageUrl":"http://abs.xxxxxxxxxxxxx.png",
"TwitterName":null}
</string>

下面是我在 Twitter 上发布推文的代码,但这里他们使用 Twitter 登录。 我不想登录。

请指导我,或者如果可能的话,请提供一些示例代码。

我正在使用 twitter4j 库。

public class MainActivity extends Activity implements OnClickListener { 

// Constants

/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */

static String TWITTER_CONSUMER_KEY = "xxxxxxxxxxxxxxxxxx";
static String TWITTER_CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";


// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

Button btnLoginTwitter;
Button btnUpdateStatus; // This is responsible for tweet updation
Button btnLogoutTwitter;
EditText txtUpdate;

ProgressDialog pDialog;

// Twitter
private static Twitter twitter;
private static RequestToken requestToken;

// Shared Preferences
private static SharedPreferences mSharedPreferences;

// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}




/*
RequestToken reqToken = (RequestToken) session.getAttribute(REQUEST_TOKEN);
session.removeAttribute(REQUEST_TOKEN);

if (!reqToken.getToken().equals(oauthToken)) {
throw new TwitterException("Wrong oauth_token");
}
AccessToken token = twitter.getOAuthAccessToken(reqToken);
*/


// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);

// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);

btnLoginTwitter.setOnClickListener(this);

btnUpdateStatus.setOnClickListener(this);

btnLogoutTwitter.setOnClickListener(this);

/**
* This if conditions is tested once is redirected from twitter page.
* Parse the uri to get oAuth Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);

// Shared Preferences
Editor e = mSharedPreferences.edit();

// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes


// Hide login button
btnLoginTwitter.setVisibility(View.GONE);

// Show Update Twitter

txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);

// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();

System.out.println("--------User Id--------------"+userID);
User user = twitter.showUser(userID);

System.out.println("-------- user --------------"+user);
String username = user.getName();

System.out.println("-------- username --------------"+username);

Toast.makeText(getApplicationContext(),
Html.fromHtml("<b>Benvenuto " + username + "</b>"),
Toast.LENGTH_LONG).show();

} catch (Exception e) {
// Check log for login errors
Log.e("Errore Login", "> " + e.getMessage());
}
}
}

}

/**
* Function to login twitter
* */




private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();

TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();

try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);

System.out.println("requestToken"+requestToken);

this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
btnLoginTwitter.setVisibility(View.GONE);

// Show Update Twitter

txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);

Toast.makeText(getApplicationContext(),
"Logged in", Toast.LENGTH_LONG).show();
}
}

/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Update in corso...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

// Access Token
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println("access_token"+access_token);
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(
PREF_KEY_OAUTH_SECRET, "xxxxxxxxxxxxxxxxxxxxxxxxxxx");

System.out.println("access_token_secret"+access_token_secret);
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);

// Update status
twitter4j.Status response = twitter.updateStatus(status);

Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}

/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Tweet Send", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}

}

/**
* Function to logout from twitter It will just clear the application shared
* preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();

// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);

btnLoginTwitter.setVisibility(View.VISIBLE);
}

/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}

protected void onResume() {
super.onResume();
}

@Override
public void onClick(View view) {
if (view == btnLoginTwitter) {
loginToTwitter();
}
if (view == btnLogoutTwitter) {
logoutFromTwitter();
}
if (view == btnUpdateStatus) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();

System.out.println("----------hiiiiiiii--------------"+status);

// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
}
}

最佳答案

 ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
configurationBuilder.setOAuthAccessToken("HERE ENTER UR ACCESS TOKEN RECEIVED IN YOUR WEB SERVICE"));
configurationBuilder.setOAuthAccessTokenSecret("HERE ENTER UR ACCESS TOKEN SECRET RECEIVED IN YOUR WEB SERVICE"));
Configuration configuration = configurationBuilder.build();
final Twitter twitter = new TwitterFactory(configuration).getInstance();

new Thread(new Runnable() {

private double x;

@Override
public void run() {
boolean success = true;
try {
x = Math.random();
twitter.updateStatus(message +" "+x);
} catch (TwitterException e) {
e.printStackTrace();
success = false;
}

final boolean finalSuccess = success;

callingActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
postResponse.onFinsihed(finalSuccess);
}
});

}
}).start();

如果您有有效的访问 token 和访问 token key ,则上述方法将允许您发布推文。干杯:)

关于java - 如何使用自己的应用程序在 Twitter 上发布推文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21084222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com