I am trying to update status to twitter using twitter4j but it does not work - twitter4j

I succeeded to get every credentials(Oauth_token,Oauth_verifier).
With it, I tried to post a text to twitter account, but it always fail with error message "No authentication challenges found"
I found some solution like
"Check the time zone automatically",
"import latest twitter4j library" etc..
but after check it, still not work.
Is there anyone can show me the way.
code is like below
public static void updateStatus(final String pOauth_token,final String pOauth_verifier) {
new Thread() {
public void run() {
Looper.prepare();
try {
TwitterFactory factory = new TwitterFactory();
AccessToken accessToken = new AccessToken(pOauth_token,pOauth_verifier);
Twitter twitter = factory.getInstance();
twitter.setOAuthConsumer(Cdef.consumerKey, Cdef.consumerSecret);
twitter.setOAuthAccessToken(accessToken);
if (twitter.getAuthorization().isEnabled()) {
Log.e("btnTwSend","인증값을 셋팅하였고 API를 호출합니다.");
Status status = twitter.updateStatus(Cdef.sendText + " #" + String.valueOf(System.currentTimeMillis()));
Log.e("btnTwSend","status:" + status.getText());
}
} catch (Exception e) {
Log.e("btnTwSend",e.toString());
}
};
}.start();
}

"No authentication challenges found"
I think you are missing Access token secret in your code. That is why you are getting this exception.
Try following :
ConfigurationBuilder configurationBuilder;
Configuration configuration;
// Set the proper configuration parameters
configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
configurationBuilder
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access token
configurationBuilder.setOAuthAccessToken(ACCESS_TOKEN);
// Access token secret
configurationBuilder
.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
// Get the configuration object based on the params
configuration = configurationBuilder.build();
// Pass it to twitter factory to get the proprt twitter instance.
twitterFactory = new TwitterFactory(configuration);
twitter = twitterFactory.getInstance();
// use this instance to update
twitter.updateStatus("Your status");

I finally found the reason.
I thought parameter named 'oauth_token' , 'oauth_verifier' is member of accesstoken,
but it was not true.
I just had to pass one more way to get correct key.
and this way needs 'oauth_token' , 'oauth_verifier' to get accesstoken.
This code must add one more code below:
mAccessToken = mTwitter.getOAuthAccessToken(REQUEST_TOKEN,OAUTH_VERIFIER);

Related

How can I get "Amazon.Extensions.CognitoAuthentication.CognitoUserSession.IDToken" From AWSCredentials?

I want get "Amazon.Extensions.CognitoAuthentication.CognitoUserSession.IDToken" From AWSCredentials.
I have AWSCredentials From Oauth Google Login.
public AWSCredentials GetAWSCredentials_Google(string token)
{
CognitoAWSCredentials credentials = new CognitoAWSCredentials(FED_POOL_ID, regionTable[REGION]);
credentials.AddLogin("accounts.google.com", token);
return credentials;
}
And, I use EC2 Instance and my ubuntu server is in there. Also, I was originally using a method of accessing the server by receiving a membership from Cognito User Pool, so I was using the following code.
private IEnumerator sendPostUser()
{
string uri = rootUrl + "/user";
string json = "{ ... }";
byte[] jsonData = System.Text.Encoding.UTF8.GetBytes(json);
using (UnityWebRequest request = UnityWebRequest.Post(uri, json))
{
if (request.uploadHandler != null)
request.uploadHandler.Dispose();
request.disposeUploadHandlerOnDispose = true;
request.disposeDownloadHandlerOnDispose = true;
request.uploadHandler = new UploadHandlerRaw(jsonData);
/* Header */
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("token", cloud_acess.GetComponent<ControlCloud>().cognitoUser.SessionTokens.IdToken);
/* Send Message */
yield return request.SendWebRequest();
...
}
By the way, there was a problem with this code "request.SetRequestHeader("token", cloud_acess.GetComponent().cognitoUser.SessionTokens.IdToken);".
This cognitouser means Amazon.Extensions.CognitoAuthentication.CognitoUser.
My Project get CognitoUser using user's ID and PW, and get AWSCredentials using this Cognitouser. But Google Login doesn't this process and just get credentials.
So, I can't get "cognitoUser.SessionTokens.IdToken". It makes me cannot to request anything from ec2 server.
How Can i get this? What should I do if the premise of this problem itself is wrong?
I tried to put all the tokens I received when I logged in to Google and the tokens I received as credentials in the header.But I failed.

How do I create an AlertsClient from an Azure Active Directory secret? [duplicate]

My company is looking into reporting on Azure. We only want our customers to give us read only credentials for us to use. I did some research and it looks like Azure Active Directory does just that. So I'm looking to authenticate using a read only Azure Directory Application.
To get me started I was following this blog on using the Management API via Azure Active Directory.
https://msdn.microsoft.com/en-us/library/azure/dn722415.aspx
Aside from the approach show being very unfriendly, it doesn't work =(
I get this error after logging in as a global administrator:
"AADSTS90014: The request body must contain the following parameter: 'client_secret or client_assertion'."
Did some research and found this style of authentication was for native app and NOT web apps (despite what the blog post saying other wise..). So I made a tweak. My GetAuthorizationHeader now looks like this:
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
I am able to get the Access Token (yay). But now when I try to use this with the Azure Management library client I get this error:
"ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription."
I double checked my permissions in my application. It looked good. I tried giving full access to everything to see if that would have made a difference.
I double checked my tenantId, clientId, and subscriptionId, all looked good.
I made sure the subscription I'm using is pointed to the AD my application is in.
I tried making a new secret key.
My guess is this is the issue:
However in this UI I am unable to select any values for that property. I'm unsure if this is the result of a bug or an unfinished feature.
Am I missing something here?
Thanks
Here's my full code for reference:
class Program
{
static void Main(string[] args)
{
var token = GetAuthorizationHeader();
var credential = new TokenCloudCredentials(ConfigurationManager.AppSettings["subscriptionId"], token);
using (var computeClient = new ComputeManagementClient(credential))
{
var images = computeClient.VirtualMachineOSImages.List();
}
}
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
EDIT:
Progress has been made. As I discussed with Gaurav, I needed to ditch the Azure Management Library because as of right now it does not seem to support Azure Resource Manager (ARM) API! So instead I did raw web requests. And it works as intended. If I remove role access off my AD Application I get access denied. When I have it I get back data.
One thing I'm not sure about is making it so my application is auto-adding to new resources.
Also, Is there a way to list Resource Groups that are accessible for my AD Application?
New code:
class Program
{
static void Main(string[] args)
{
var token = GetAuthorizationHeader();
string subscriptionId = ConfigurationManager.AppSettings["subscriptionId"];
string resourceGroupName = ConfigurationManager.AppSettings["resourceGroupName"];
var uriListMachines = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualmachines?api-version=2015-05-01-preview", subscriptionId, resourceGroupName);
var t = WebRequest.Create(uriListMachines);
t.ContentType = "application/json";
t.Headers.Add("Authorization", "Bearer " + token);
var response = (HttpWebResponse)t.GetResponse();
string result = "";
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
//Original Attempt:
//var credential = new TokenCloudCredentials(ConfigurationManager.AppSettings["subscriptionId"], token);
//using (var client = CloudContext.Clients.CreateComputeManagementClient(credential))
//{
// var images = client.VirtualMachineVMImages.List();
//}
}
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
EDIT EDIT:
I figured out my hung up. Resources created in the OLD portal will get it's own distinct resource group.
From what I can tell you can not add a resource made in the old portal existing resource group (boooo). Resources created in the new portal will be able to assign the resource to an existing group (aka one that gives a role access to my AD Application).
This is such a mess! But at least I know what is going on now.
I believe you're on the right track as to why you're running into this problem.
Here's what's happening:
Essentially permission to execute Service Management API is a delegated permission and not an application permission. In other words, the API is executed in context of the user for which the token is acquired. Now you are getting this token for your application (specified by client id/secret). However your application doesn't have access to your Azure Subscription because the user record created for this application in your Azure AD is of type Service Principal. Since this Service Principal doesn't have access to your Azure Subscription, you're getting this Forbidden Error (I must say that the error is misleading because you're not using certificate at all).
There are a few things you could do:
Switch to Azure Resource Manager (ARM) API - ARM API is the next generation of Service Management API (SM API) and Azure is moving towards this direction only. It exclusively works off of Azure AD token. If possible, make use of that to manage your Azure resources (though you need to keep in mind that as of today not all Azure resources can be managed through ARM API). They way you do it is take your Service Principal and assign it to a particular role using new Azure Portal. Please see this link for more details on this: https://azure.microsoft.com/en-in/documentation/articles/resource-group-create-service-principal-portal/.
Use X509 Certificate - You can always use X509 Certificate based authorization to authorize your SM API requests. Please see this link for more details on that: https://msdn.microsoft.com/en-us/library/azure/ee460782.aspx#bk_cert. The downside of this approach is that the application (or whosoever has access to this certificate) will get full access to your Azure Subscription and can do everything there (including deleting resources).
Acquire token for a user instead of an application - This is another approach you can take. Essentially ask your users to login into Azure AD through your console application and acquire token for that user. Again, please keep in mind that this user must be a Co-Admin in your Azure Subscription and will have full access to your Azure Subscription as with SM API there's no concept of Role-based access control.

Cloud SQL Admin API

I've been working with sqladmin-appengine-sample and the v1beta3 json API.
The Java code is running on App Engine. oauth2.
I can get it to work where when the currently logged in user is the app owner, but what I think I need is something like AppIdentityCredential so that the app can access any of the SQL instances it has access to regardless of the currently logged in user.
How do I do this?
Do I need to use a service account?
The short answer is that I could not get AppIdentityCredential to work, but setting up a Service Account credential did work. Here is the code:
Set<String> oAuthScopes = new HashSet<String>();
oAuthScopes.add(SQLAdminScopes.CLOUD_PLATFORM);
oAuthScopes.add(SQLAdminScopes.SQLSERVICE_ADMIN);
// service account credential
GoogleCredential credential;
try {
File p12File = new File(servletContext.getResource(PK12_FILE_NAME).toURI());
credential = new GoogleCredential.Builder()
.setTransport(Utils.HTTP_TRANSPORT)
.setJsonFactory(Utils.JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_ID)
.setServiceAccountScopes(oAuthScopes)
.setServiceAccountPrivateKeyFromP12File(p12File)
.build();
} catch (Exception e) {
throw new SecurityException(e);
}
// build the SQLAdmin object using the credentials
this.sqlAdmin = new SQLAdmin.Builder(Utils.HTTP_TRANSPORT, Utils.JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
String timestamp = new Date().toString().replace(" ", "_").replace(":", "_");
ExportContext exportContent = new ExportContext();
exportContent.setDatabase(Arrays.asList(database_name));
exportContent.setKind("sql#exportContext");
exportContent.setUri("gs://"+GCS_BUCKET_NAME+"/"+database_name+"_"+timestamp+".mysql");
InstancesExportRequest exportRequest = new InstancesExportRequest();
exportRequest.setExportContext(exportContent);
// execute the exportRequest
this.sqlAdmin.instances().export(APPLICATION_NAME, instance_name, exportRequest).execute();

How can i post the feed to facebook page as admin using c# sdk?

I want to update the facebookpage using c# sdk. I have partially successful with this, the problem is whenever I post messages to the page, post is visible only for admin(i am the admin of the page)is logged In. I want the post or feed to be visible to every one who visit the page.
(even admin is logged out post's are not visible to admin also)
The following code i am trying to achieve
public ActionResult FacebookPagePost()
{
string app_id = "xxxx";
string app_secret = "xxx";
string scope = "publish_stream,manage_pages";
string page_Id = "xxX";
if (Request["code"] == null)
{
return Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
try
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic fbAccounts = client.Get("/me/accounts");
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://pic.com/pic.png";
messagePost.link = "http://www.examplearticle.com";
messagePost.name = "name goes here";
messagePost.description = "description goes here";
//Loop over the accounts looking for the ID that matches your destination ID (Fan Page ID)
foreach (dynamic account in fbAccounts.data) {
if (account.id == page_Id)
{
//When you find it, grab the associated access token and put it in the Dictionary to pass in the FB Post, then break out.
messagePost.access_token = account.access_token;
break;
}
}
client.Post("/" + page_Id + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
}
catch (Exception e)
{
}
}
}
1) Create a Facebook App at: developers.facebook.com and get yourself an APPID and APPSECRET. (there are a lot of tutorials online for doing this so I will skip repeating it)
2) Go to: http://developers.facebook.com/tools/explorer and choose your app from the dropdown and click "generate access token".
3) After that do the following steps here:
https://stackoverflow.com/questions/17197970/facebook-permanent-page-access-token to get yourself a permanent page token.
(I can not stress this enough, follow the steps carefully and thoroughly)*
*I have tool I built that does this for me, all I enter is the APPID, APPSECRET and ACCESSTOKEN which the tool then generates a permanent page token for me. Anyone is welcomed to use it and help make it better,
https://github.com/devfunkd/facebookpagetokengenerator
=========================================================================
Ok at this point you should have your APPID, APPSECRET and a PERMANENT PAGE TOKEN.
=========================================================================
In your Visual Studio solution:
4) Using Nuget:Install-Package Facebook
5) Implement the Facebook client:
public void PostMessage(string message)
{
try
{
var fb = new FacebookClient
{
AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
};
dynamic result = fb.Post("me/feed", new
{
message = message
});
}
catch (Exception exception)
{
// Handle your exception
}
}
I hope this helps anyone who is struggling to figure this out.

Twitter 4j with Netbeans

First time poster, but I'm really stuck.
I'm working on a little project and I'm trying to send out a tweet using a netbeans project. I'm using twitter4j and it seems like things have recently changed to where you have to use their OAuth function. I've created an application on twitter and tried some code but I keep getting this error:Exception in thread "main" connect timed outRelevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=b2b52c28 or
http://www.google.co.jp/search?q=1b442895
TwitterException{exceptionCode=[b2b52c28-1b442895 b2b52c28-1b44286b], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:200)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.TwitterImpl.post(TwitterImpl.java:1929)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:433)
at login.Login.start(Login.java:36)
at login.Login.main(Login.java:63)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:213)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.http.HttpClient.New(HttpClient.java:316)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
... 6 more
Java Result: 1
I'm not entirely sure what I'm doing wrong. Below is the code I've tried.
package login;
import java.io.IOException;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class Login {
private final static String CONSUMER_KEY = "******";
private final static String CONSUMER_KEY_SECRET =
"******";
public void start() throws TwitterException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
// here's the difference
String accessToken = getSavedAccessToken();
String accessTokenSecret = getSavedAccessTokenSecret();
AccessToken oathAccessToken = new AccessToken(accessToken,
accessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
// end of difference
twitter.updateStatus("Hi, im updating status again from Namex Tweet for Demo");
System.out.println("\nMy Timeline:");
// I'm reading your timeline
ResponseList list = twitter.getHomeTimeline();
/* for (Status each : list) {
System.out.println("Sent by: #" + each.getUser().getScreenName()
+ " - " + each.getUser().getName() + "\n" + each.getText()
+ "\n");
}*/
}
private String getSavedAccessTokenSecret() {
// consider this is method to get your previously saved Access Token
// Secret
return "oC8tImRFL6i8TuRkTEaIcWsF8oY4SL5iTGNkG9O0Q";
}
private String getSavedAccessToken() {
// consider this is method to get your previously saved Access Token
return "102333999-M4W1Jtp8y8QY8RH7OxGWbM5Len5xOeeTUuG7QfcY";
}
public static void main(String[] args) throws Exception {
new Login().start();
}
}
Could I suggest an alternative route..
I have recently been messing around with twitter4j and I approached this slightly differently - I found a nice and easy way to authenticate the client using a ConfigurationBuilder object and passing this to the factory that is getting the instance of the Twitter object you need.
package main;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Base {
protected Twitter twitter;
//protected TwitterStream twitterStream;
private ConfigurationBuilder configBuilder;
public Base(){
configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true);
configBuilder.setOAuthConsumerKey("[consumer key here]");
configBuilder.setOAuthConsumerSecret("[consumer secret key here]");
configBuilder.setOAuthAccessToken("[OAuthAccessToken here]");
configBuilder.setOAuthAccessTokenSecret("[secret OAuthAccessToken here]");
//use the ConfigBuilder.build() method and pass the result to the TwitterFactory
TwitterFactory tf = new TwitterFactory(configBuilder.build());
//you can now get authenticated instance of Twitter object.
twitter = tf.getInstance();
}
}
You could then extend this class with sub classes that implement the functionality you require or just create the ConfigurationBuilder/TwitterFactory/Twitter objects elsewhere in your code.
Below I have implemented a class that creates status' and can return the Status object that holds additional information such as createdAt() and the ID etc etc.
package main;
import twitter4j.Status;
import twitter4j.TwitterException;
public class StatusUpdater extends Base{
public StatusUpdater(){}
public Status updateStatus(String statusToUpdate) throws TwitterException{
Status status = twitter.updateStatus(statusToUpdate);
System.out.println("statusToUpdate: " + status + ".");
return status;
}
}
Then you can use the following statement to create the status. This can be done from mbean/ejb/servlet etc.
try {
StatusUpdater statusUpdater = new StatusUpdater();
String statusTextToSet = "test status";
Status updatedStatus = statusUpdater.updateStatus(statusTextToSet);
System.out.println("Created at: " + updatedStatus.getCreatedAt());
} catch (TwitterException tex) {
System.out.println(tex.getErrorMessage());
}
More info on the configuration process here
Your code looks ok. Have you confirmed your definitely using the correct consumer key and secret for your app? Try twitter.verifyCredentials() to see if you get the same error, or a more specific error.
If you're correcting to the net via a proxy, you will need to include your proxy settings to allow the connection to succeed, details can be found here http://twitter4j.org/en/configuration.html#HTTP%20proxy%20server
As an aside, you may want to remove you access token and secret from your post, if they're still valid then someone could login to your account with them.