Error on twitter api 1.1 - java

protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean isSuccess = false;
try {
//Consumer key
String consumerKey = STATICVALUES.consumerKey;
//Consumer secret
String consumerSecret = STATICVALUES.consumerSecret;
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey ,consumerSecret);
AccessToken accessToken = new AccessToken(params[0], params[1]);
twitter.setOAuthAccessToken(accessToken);
twitter.updateStatus(params[2]);
Log.e("TAG", "true");
isSuccess = true;
}
catch (TwitterException e) {
isSuccess = false;
Log.e("TAG", "fail");
e.printStackTrace();
}
return isSuccess;
}
this is my code.
i use twitter4j-2.0.2 core. and i have a error, as you know, error about api 1.1
so i add twitter4j 3.0.3 core, but nothing's change.
i search about twitter api 1.1, but someone just add twitter4j 3.0.3 core, someone need change xml to json.
i write to editbox, and click button, this text send tiwtter.
what can i do? i need help!

Check this out.
https://github.com/vshivam/privly-android/blob/master/src/ly/priv/mobile/TwitterLinkGrabberService.java#L120
Dependencies :
/privly-android/libs/signpost-commonshttp4-1.2.1.2.jar
/privly-android/libs/signpost-core-1.2.1.2.jar
/privly-android/libs/twitter4j-core-3.0.3.jar

Related

How to get direct link of remote video from embedded url within a url in Android using JSoup?

I had asked the question previously about how to retrieve the embedded url for a video file and have successfully done so. Now I have a different issue. The json response for a WUnderground API webcam response gives the following url:
https://www.wunderground.com/webcams/cadot1/902/show.html
Using JSoup and per the answer to my initial issue I was able to get this embedded link:
https://www.wunderground.com/webcams/cadot1/902/video.html?month=11&year=2016&filename=current.mp4
While trying to "stream" the video from that url to a VideoView, I kept getting the error "cannot play video". Upon looking at the source for that link I noticed that the video file that needs to be played is not referenced in html but rather javascript. How can I get the direct link for the video file that needs to be played? Using JSoup or other process?
The source for the url https://www.wunderground.com/webcams/cadot1/902/video.html?month=11&year=2016&filename=current.mp4 shows the following for the needed video file within a <script> bracket:
url: "//icons.wunderground.com/webcamcurrent/c/a/cadot1/902/current.mp4?e=1480377508"
I am using JSoup to get the embedded url for the video from the response url like so:
private class VideoLink extends AsyncTask<Void, Void, Void> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setTitle("JSOUP Test");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// for avoiding javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
System.setProperty("jsse.enableSNIExtension", "false");
// WARNING: do it only if security isn't important, otherwise you have
// to follow this advices: http://stackoverflow.com/a/7745706/1363265
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
public X509Certificate[] getAcceptedIssuers(){return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
;
}
// Connect to the web site
Document doc = Jsoup.connect(TEST_URL).get();
Elements elements = doc.getElementsByClass("videoText");
// Get the html document title
for (Element link : elements) {
String linkHref = link.attr("href");
// linkHref contains something like video.html?month=11&year=2016&filename=current.mp4
// TODO check if linkHref ends with current.mp4
title = linkHref;
}
} catch (IOException e) {
e.printStackTrace();
mProgressDialog.dismiss();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set title into TextView
resultTxt.setText(title);
String resVid = TEST_URL;
Log.d(TAG, "URL: " + resVid);
Uri resUri = Uri.parse(resVid);
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(
MainActivity.this);
mediacontroller.setAnchorView(resultVidVw);
// Get the URL from String VideoURL
Uri video = Uri.parse(resVid);
resultVidVw.setMediaController(mediacontroller);
resultVidVw.setVideoURI(video);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
resultVidVw.requestFocus();
resultVidVw.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
mProgressDialog.dismiss();
resultVidVw.start();
}
});
}
}
Please note that I need to do this on every JSONObject in the response array.
This is how you can GET the file:
(Notice: the Extraction part only works with current html of the site and if that changes, it may not work correctly!)
String url = "https://www.wunderground.com/webcams/cadot1/902/video.html";
int timeout = 100 * 1000;
// Extract video URL
Document doc = Jsoup.connect(url).timeout(timeout).get();
Element script = doc.getElementById("inner-content")
.getElementsByTag("script").last();
String content = script.data();
int indexOfUrl = content.indexOf("url");
int indexOfComma = content.indexOf(',', indexOfUrl);
String videoUrl = "https:" + content.substring(indexOfUrl + 6, indexOfComma - 1);
System.out.println(videoUrl);
[Output: https://icons.wunderground.com/webcamcurrent/c/a/cadot1/902/current.mp4?e=1481246112]
Now you can get the file by specifying .ignoreContentType(true) in order to avoid org.jsoup.UnsupportedMimeTypeException and .maxBodySize(0) to remove the limit on file size.
// Get video file
byte[] video = Jsoup.connect(videoUrl)
.ignoreContentType(true).timeout(timeout).maxBodySize(0)
.execute().bodyAsBytes();
I don't know if you can play it in Android or not but I think you can save it using org.apache.commons.io.FileUtils (I tested it in Java SE but not Android development environment.)
// Save video file
org.apache.commons.io.FileUtils.writeByteArrayToFile(new File("test.mp4"), video);

Share text on Facebook using sdk

I am working on an android app in which I am sharing content on facebook. I am able to share link, image. But i am unable to send when i only post text on facebook. I did not get any thing. I am using following code for share on facebook.
Bundle bundle = new Bundle();
bundle.putString("name", webPageContent);
bundle.putString("message", webPageContent);
FeedDialogBuilder feedDialog = new WebDialog.FeedDialogBuilder(FacebookShareActivity.this,Session.getActiveSession(),bundle)
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
// TODO Auto-generated method stub
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null)
{
Toast.makeText(FacebookShareActivity.this, "Posted story, id: "+postId, Toast.LENGTH_SHORT).show();
}
}
}
});
feedDialog.build().show();
Please see the docs for the feed dialog: https://developers.facebook.com/docs/sharing/reference/feed-dialog/v2.2
As you can see, there's no message property. This is because prefilling the status update for the user is against platform policies.

java how do I get the latest tweet for a particular user

I would like to get latest tweet from #Citi in java. I thought I should use twitter4j (BUT anything easier would be fine). I cannot tell from the documentation how to supply the "user" i.e. #Citi?
public static void main(String[] args) {
// TODO Auto-generated method stub
Twitter twitter = new TwitterFactory().getInstance();
List<Status> statusList = null;
try {
statusList = twitter.getUserTimeline("#Citi");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Status status : statusList) {
System.out.println(status.toString());
}
}
I tried the above but it crashes on getUserTimeline.
The code must create an instance of ConfigurationBuider and pass in your Twitter API credentials. Add the following.
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("Your Cosumer Key")
.setOAuthConsumerSecret("Your Consumer Secret")
.setOAuthAccessToken("Your Access Token")
.setOAuthAccessTokenSecret("Your Access Token Secret");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<Status> statusList = null;
try {
statusList = twitter.getUserTimeline("#Citi");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Status status : statusList) {
System.out.println(status.toString());
}
}
A Twitter API account is required to use the Twitter API. Twitter requires this so they can track who is using their API and conduct activities such as rate limiting. To obtain a Twitter API account, first create a Twitter account, then create the API account at this page: https://dev.twitter.com/
have you looked into the provided examples?
http://twitter4j.org/en/code-examples.html
You need to have OAuth credentials configured in your twitter4j.properties
See: http://twitter4j.org/en/configuration.html
Regards
Create application in developer and you'll get consumer keys for the application. These are application specific keys to identify your application. Then you'll have to supply access tokens, which are user specific keys. With the combination of these four, Any application with any user given, you can get its tweets. If you want to get tweets in real time, user Streaming API, otherwise you can get last 20 Tweets with the code you posted.

Using Twitter4j to get favorited count for a particular tweet

I am new to the twitter4j api, is there any way of getting no of favorite count for a particular tweet using twitter4j. I am using api version 3.0.3 for Twitter4j.
In documentation the method getFavoriteCount() is present but the same method gives compilation error in code. Should I use different version of jar file?
public static void main(String[] args) {
ConfigurationBuilder cb= new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("**************************");
cb.setOAuthConsumerSecret("**************************");
cb.setOAuthAccessToken("*******************************");
cb.setOAuthAccessTokenSecret("*****************************");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
User user = null;
try {
user = twitter.verifyCredentials();
} catch (TwitterException e1) {
e1.printStackTrace();
}
String[] test = new String[]{"teststr"};
ResponseList<User> users;
try {
users = twitter.lookupUsers(test);
for (User user1 : users) {
if (user1.getStatus() != null)
{
Paging paging = new Paging(1, 40);
ResponseList<Status> statusess = twitter.getUserTimeline(user1.getName(),paging);
for (Status status3 : statusess)
{
long retweetCount = status3.getRetweetCount();
long favoriteCount = status3.getFavoriteCount();/** this line gives compilation error saying the method getFavoriteCount() is undefined for the type Status**/
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
}
Unfortunately, it seems like the JavaDocs on the Twitter4J site linked next to the 3.0.3 release are not correct. The actual docs are here - you can see that getFavoriteCount() isn't present in these.
It looks like Status#getFavoriteCount() was only introduced in 3.0.4. So yes, you need to upgrade from 3.0.3 in order to use this method.
Although be aware that version 3.0.4 looks like it is under active development presently.
Although you have already found and marked an answer, let me provide an alternate to switching the Twitter4J version.
When using a method similar to what you are using, I had searched a lot and finally found the solution in an entirely unrelated post. Here is how you can get the Favorite count of tweets:
NOTE: This is what I use in an Android app of mine.
First, in your ConfigurationBuilder cb instance, add this one line:
cb.setJSONStoreEnabled(true);
This will return all results in a JSON format. Strangely, getting a JSON result it provides you that value.
Now, to fetch the Tweets:
try {
Paging paging = new Paging(initPagingOffset, 200);
statuses = twitter.getHomeTimeline(paging);
String strTweets = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strTweets);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
..... // PARSE ANY OTHER DATA YOU MIGHT NEED FOR DISPLAYING THE TWEETS
String FAV_COUNT = JOTweet.getString("favorite_count");
}
} catch (TwitterException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

Java Google Youtube Data API:: Unauthorized

I wanted to upload a video on youtube using Java Google Data API. I got the following cod from the Google Data Api documentation to upload a video.The only thing i need to change in this code in Client ID and Porduct key. i am using followinf method to authenticate
YouTubeService service = new YouTubeService(clientID, developer_key);
Client key is my Google Email id , tried with with wasy,
only provided Username e,g. "sampleuser"
or complete Gmail id e.g. "sampleuser#gmail.com" or "smapleuser#googlemail.com"
i got developer key by logging my Google mail id as mentioned "smapleuser#googlemail.com"
but i always got following exception
com.google.gdata.util.AuthenticationException: Unauthorized
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.media.MediaService.insert(MediaService.java:400)
at YouTube.videoUpload(YouTube.java:115)
at YouTube.main(YouTube.java:43)
here is my code for video Upload
YouTubeService service = new YouTubeService("sampleuser#gmail.com",
"fakegoogleapplicationidjsuttoshowthatimgivingidhere");
// YouTubeService service = new YouTubeService("My Application");
VideoEntry newEntry = new VideoEntry();
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent("My Test Movie");
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Autos"));
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("cars");
mg.getKeywords().addKeyword("funny");
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent("My description");
mg.setPrivate(false);
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "mydevtag"));
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "anotherdevtag"));
newEntry.setGeoCoordinates(new GeoRssWhere(37.0,-122.0));
// alternatively, one could specify just a descriptive string
// newEntry.setLocation("Mountain View, CA");
MediaFileSource ms = new MediaFileSource(new File("D:\\maths.mp4")
, "video/quicktime");
newEntry.setMediaSource(ms);
// "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
String uploadUrl =
"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
try {
VideoEntry createdEntry = service.insert(new URL(uploadUrl), newEntry);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
please help , unable to find solution. thank you so much..looking for response
Try to add
service.setUserCredentials("email_here", "password_here");

Categories