I want to auto tweet from a java application. What is the simplest way to do it? Can i avoid using libraries like Twitter4j etc.,
I need an implementation for a simple api like
Tweet(username, password, message)..
Thank you.
I recommend you to use twitter4j and using this you can create oAuth requests easily.
Twitter rate limits apply to desktop application and it is 150/hour.
Twitter does not support basic authentication with username and password anymore.
You are required to create an application in twitter and using the consumer key and secret only you can access your twitter account.
If you are going to access the twitter by a desktop application then you have to select
Application Type: as "Client" while creating the application.
Then you can use the syntax below to update your status in twitter
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(oAuthAccessToken)
.setOAuthAccessTokenSecret(oAuthAccessTokenSecret);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
twitter.updateStatus("This is a test message"); //ThrowsTwitterException
I hope this helps you... Please let me know if this is not the answer you were looking for.
Implementing your own oAuth request involve creating signature that for me was complicated and it is sensitive to time and time format that we send.
Twitter has a REST web API, and a lot of documentation. For reference:
http://dev.twitter.com/doc
While you don't necessarily need Twitter4J, it does make it easier. Otherwise you would need to assemble your own URL requests and take care of authentication. They offer more than one style:
http://dev.twitter.com/pages/auth_overview
Traditionally, OAuth is the preferred style for desktop application to web server integration--but that protocol is a bit complicated.
There's nothing that says you can't create your Tweet() method to hide away the details of using Tweet4J or hand-rolling the request yourself.
I want to auto tweet from a java
application.
I hope you are not spamming.. :D
Try this one: http://code.google.com/p/java-twitter/
You can wrap the example code into:
public void tweet(String username, String password, String message){
Api api = Api.builder().username(username).password(password).build();
api.updateStatus(message).build().post();
}
And then call it as tweet.(username,pass,message)
Looks simple to me.
Spring Social? I saw a demo of it at SpringOne - looked pretty cool, although I personally do not have a use for it, and therefore haven't done much besides read about it. You get some OAuth capability and templates for interacting with the major social networking sites out of the box.
Related
With the oldest PayPal API, setting the return URL when a checkout is accomplishment, or when checkout is eliminated is easy, as described here:
Payment payment = new Payment();
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(cancelUrl);
redirectUrls.setReturnUrl(successUrl);
payment.setRedirectUrls(redirectUrls);
How can I accomplished this goal with new PayPal API?
I have already setting an url return (google.com for testing) in my sandbox account but it seems not work..
Which new API? There are several. Are you using the Checkout-Java-SDK? The best integrations do not use a redirect, and hence do not need a return URL.
Instead, implement two routes on your server that return JSON data -- one for 'Create Order' and one for 'Capture Order', documented here.
The approval flow to pair those two routes with is: https://developer.paypal.com/demo/checkout/#/pattern/server
This flow does not redirect away, hence there is no need or use for a return URL and if specified it will be ignored.
I have already setting an url return (google.com for testing) in my sandbox account but it seems not work.
That is for non-API integrations that use a link or HTML form post. There is no API integration that pays any attention to that profile setting.
I know this is an old post now but with REST API, there is a way to return these URLs. If you go to https://developer.paypal.com/api/orders/v2/ and click the application_context object link, you would be able to see the other details you can add to pass into your payload -- eg. brand_name, return_url, cancel_url etc. I do not think that Paypal has provided now an SDK but would love to know if there is. Right now, only the REST endpoints and payloads are available on their developer page.
I've been researching networking in android and have become familiar with the basic concepts. However, I've recently been working on an app intended for use by my school as a gradebook/assignment display of sorts. My school uses the following online gradebook: https://parents.mtsd.k12.nj.us/, and currently I'm trying to allow students to input their login credentials into my app which will then try to retrieve their respective information and display it in a gridview. However, I have never attempted to log in to a website from an android app before parsing data (I have gone through several similar questions but I am still a little confused)
Any help is appreciated!
[edit] After logging in I will use import.io to display gradebook data, website does not have api
If I understand You clearly u need to :
Connect to site using HttpURLConnection with user creditentials (do Post request to login page)
Obtain cookies from request (my favorite way is to parse - copy appropriate header field)
Use obtained cookies with HttpURLConnection.setRequestProperty("Cookie",obtainedCookies) and do another request(to user data page).
Get input stream
Parse stream
(to obtain Document "html" u can use jsoup example:
Document doc = JSoup.parse(stream, null, "");
Show data
GUIDELINES:
cookie how to
Most useful example
Caution:
-any http requests needs to be done outside main thread (ui thread) - u can use async task for this or intent service
EDIT on questions:
you ask whether to use Jsoup to handle connection?
my answer is NO!
Jsoup is a PARSER by using HttpURLConnection u gain full control over HTTP request so for example u can handle some specyfic exceptions or request propertiers which jsoup is not capable! from my experience after a while I start to disassemble the libraries and learn from them the basics and use parts of them in my code!
You could make a WebView with a custom HTML file which has a login and password field, and then have the HTML file run the same script as the website to log them in.
I'm trying to integrate Google APIs inside a project (Thesis project) and I have some doubts and questions. So, here it is the scenario:
I wrote a back-end application in Java that runs solely from a command-line and has absolutely no interaction with a user. Its goal is to allow communication and interaction between sensors and actuators. Everything works great. Now I'd like to integrate something in order to let the sensors backup data both with a certain periodicity and due to some detected threshold value. So I thought, why not trying with Google Drive. The first very useful links have been:
https://developers.google.com/drive/web/quickstart/quickstart-java
https://developers.google.com/accounts/docs/OAuth2InstalledApp
Quick start examples work like a charm. However it requires quite a bit of settings: create a project inside the Developer Console (therefore an account), enable Drive API, then create a Client ID and a Client Secret. Once you've done these steps, you can hard-coded client ID and secret to form the request URL for google drive. Then you're kindly asked to enter the url in a browser, log in if you're not, accept and finally copy and paste into your console the authorization code for obtaining an access token. Wow, quite a security proccess. But hey, I completely agree with it, above all in a scenario where we have either a web app, a smartphone app or a web service that needs users' authentication and authorization in order to let the app doing its job by accessing someone else account. But in my case, I just would like that sensors will backup data on my google drive.
These facts lead to my first question: in order to use Google APIs (Drive in this case), do I have to create a project anyway? Or is there another approach? If I'm not wrong, there aren't other ways to create a client Id and secret without creating a project inside the Developer Console. This puzzles me a lot. Why should I create a project to use basically some libraries?
So, let's assume the previous as justifiable constraints and move on the real question: how to automate the authentication process? Given my scenario where a sensor (simply a Java module) want to backup data, it would be impossible to complete all that steps. The google page about OAuth 2.0 has a great explanations about different scenarios where we can embed the authentication procedure, included one for "devices with limited input capabilities". Unluckily, this is more complicated then the others and requires that "The user switches to a device or computer with richer input capabilities, launches a browser, navigates to the URL specified on the limited-input device, logs in, and enters the code." (LOL)
So, I didn't give up and I ended up on this post that talks about OAuth Playground: How do I authorise an app (web or installed) without user intervention? (canonical ?). It really looks like as a solution for me, in particular when it says:
NB2. This technique works well if you want a web app which access
your own (and only your own) Drive account, without bothering to write
the authorization code which would only ever be run once. Just skip
step 1, and replace "my.drive.app" with your own email address in step
5.
However if I'm not wrong, I think that OAuth Playground it's just for helping test and debug projects that use Google APIs, isn't it? Moreover, Google drive classes such as GoogleAuthorizationCodeFlow and GoogleCredential (used inside the Java quick start example) always need Client ID, Client Secret and so on, which brings me to point zero (create a project and do the whole graphical procedure).
In conclusion: is there a way to avoid the "graphical" authentication interaction and convert it into an automated process using only Drive's APIs without the user intervention? Thanks a lot, I would be grateful for any tip, hint, answer, pointer :-)
This is just a snippet of code that I wrote thanks to pinoyyid suggestions. Just to recap what we should do in this case (when in your program there isn't a user interaction for completing all the Google GUI authentication process). As reported in https://developers.google.com/drive/web/quickstart/quickstart-java
Go to the Google Developers Console.
Select a project, or create a new one.
In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the Drive API.
In the sidebar on the left, select Credentials.
In either case, you end up on the Credentials page and can create your project's credentials from here.
From the Credentials page, click Create new Client ID under the OAuth heading to create your OAuth 2.0 credentials. Your application's client ID, email address, client secret, redirect URIs, and JavaScript origins are in the Client ID for web application section.
The pinoyyd post is neater and get straight to the point: How do I authorise a background web app without user intervention? (canonical ?)
Pay attention to step number 7
Finally the snippet of code is very simple, it's just about sending a POST request and it's possible to do that in many ways in Java. Therefore this is just an example and I'm sure there is room for improvements ;-)
// Both to set access token the first time that we run the module and in general to refresh the token
public void sendPOST(){
try {
URL url = new URL("https://www.googleapis.com/oauth2/v3/token");
Map<String,Object> params = new LinkedHashMap<>();
params.put("client_id", CLIENT_ID);
params.put("client_secret", CLIENT_SECRET);
params.put("refresh_token", REFRESH_TOKEN);
params.put("grant_type", "refresh_token");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader in_rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
// Read response body which should be a json structure
String inputLine;
StringBuilder responseBody = new StringBuilder();
while ((inputLine = in_rd.readLine()) != null) {
responseBody.append(inputLine);
}
in_rd.close();
//Parsing Response --> create a json object
JSONObject jsonResp = new JSONObject(responseBody);
//Modify previous access token String
ACCESS_TOKEN = jsonResp.getString("access_token");
}
catch(MalformedURLException ex_URL){
System.out.println("An error occured: " + ex_URL.getMessage());
}
catch(JSONException ex_json) {
System.out.println("An error occured: " + ex_json.getMessage());
}
catch(IOException ex_IO){
System.out.println("An error occured: " + ex_IO.getMessage());
}
} //end of sendRefreshPOST method
Hope this snippet of code will help others that will face the same situation !
I wrote the SO post at How do I authorise an app (web or installed) without user intervention? (canonical ?)
What it describes is indeed the solution to your use-case. The key bit you'd missed is step 7 where you enter the details of your own application into the OAuth Playground. From that point, the playground is impersonating your app and so you can do the one-time authorization and obtaining a refresh token.
I am trying to connect to MS Dynamics CRM 2011 from Java. After lots of searching I came across one link in MS forums which gives a code snippet to invoke MS Dynamics CRM 2011 WS from Java.
Consuming CRM REST Service from Java
However, it does not provide much details other than an account creation step. Using this code snippet I am able to create accounts. However, I want to also use the same REST web service to retrieve accounts, create new case request, add case request to account, etc. Based on .NET examples available online I am trying to use the service.createAccountQuery() method to retrieve accounts. However, while all .NET examples uses LINQ to setup search criteria, I am clueless how to specify the subpath string in java to retrieve existing Accounts by their name/city/country etc.
Appreciate any help.
Instead of the "Account act..." line and below, use something like:
// Retrieve all accounts that the user has read access to.
string fetch1 = #"<fetch mapping=""logical"">
<entity name=""account"">
<all-attributes/>
</entity>
</fetch>";
// Fetch the results.
ExecuteFetchRequest req = new ExecuteFetchRequest();
req.FetchXml = fetch1;
ExecuteFetchResponse result1 = (ExecuteFetchResponse)service.Execute(req);
I'm unfamiliar with this proxy, but you want to call service.X where X is the Execute or RetrieveMultiple (based on what the proxy provides).
not sure if you are still looking but for anyone else looking. I had the same issue.
It is using the odata query url so the subpath is the entitySet (e.g. for account it would be AccountSet)
you can then set the filter using the .filter method and the select via the .select method.
I did notice that you can't seem to do these on seperate lines though
e.g. you can't do
Query<microsoft.crm.sdk.data.services.Account> q = service.createAccountQuery("AccountSet");
q.filter("substringof('Test',Name)");
q.select("AccountId,Name");
q.execute();
you must do
Query<microsoft.crm.sdk.data.services.Account> q = service.createAccountQuery("AccountSet").filter("substringof('Test',Name)").select("AccountId,Name");
q.execute();
Chris
My problem is I get error while trying to get request token from Yahoo. The error says Im missing oauth_callback parameter and yes I miss it because I dont need it. Ive read I need to set it to "oob" value if I dont want to use it(desktop app). And I did that but to no avail. If I set it to null the same happens. Im using OAuth for java: http://oauth.googlecode.com/svn/code/java/core/
OAuthServiceProvider serviceProvider = new OAuthServiceProvider("https://api.login.yahoo.com/oauth/v2/get_request_token",
"https://api.login.yahoo.com/oauth/v2/request_auth",
"https://api.login.yahoo.com/oauth/v2/get_token");
OAuthConsumer consumer = new OAuthConsumer("oob", consumerKey, consumerSecret, serviceProvider);
OAuthAccessor accessor = new OAuthAccessor(consumer);
OAuthClient client = new OAuthClient(new HttpClient4());
OAuthMessage response = client.getRequestTokenResponse(accessor, OAuthMessage.POST, null);
System.out.println(response.getBodyAsStream());
Have you tried using Scribe?
I also had problems with OAuth java libs so I developed that one. It's pretty much cross provider and better documented than the one you're using.
If it does not work with Yahoo you can easily extend it creating your own Provider
Hope that helps!
there is a problem in the java OAuthMassage class, I resolved it by adding to addRequiredParameters method thie line
if (pMap.get(OAuth.OAUTH_CALLBACK) == null) {
addParameter(OAuth.OAUTH_CALLBACK, consumer.callbackURL);
}
if you still have this problem I can help you: rbouadjenek#gmail.com
I haven't used that library, but it looks like it isn't properly handling the callback URL. Since OAuth 1.0a (http://oauth.net/advisories/2009-1/ and http://oauth.net/core/1.0a/), the callback URL needs to be sent in the first call to get the request token (not in the client-side call to authorise it), and it seems that this library hasn't been updated to do this (at least from looking at the code). I assume that Yahoo requires the parameter to be there.
Not sure if the original problem was ever solved, but wanted to point to a new Java OAuth SDK that Yahoo released last week:
http://developer.yahoo.net/blog/archives/2010/07/yos_sdk_for_java.html
Developers trying to access Yahoo's services via OAuth with Java may find parts of this SDK helpful.