In-app Twitter timeline without authentication? - android

Lately, I have been working on an app to see if I could do some stuff like a Twitter timeline correctly.
I created a nice little ListView, let some options link to a site, let one option call a Dialog to choose a Twitter account, and accomplished a Twitter feed viewer.
However, it doesn't seem to be possible to actually retrieve a user's timeline without authentication with Twitter? Or is it possible? If so, how do I do that?
Can I retrieve and display a user's Twitter feed without authentication, and how?

Yes, you can either use the twitter search API, which returns json formatted data, which you must parse, just search the documentation. Alternatively, you can use a direct link to a user's timeline like so:
https://twitter.com/statuses/user_timeline/user.json
EDIT: This returns the response as .json for me, next it needs to be parsed. Make sure you are parsing the response AFTER it has been received, it looks like you are starting the request and then jumping to parsing it, before the request is complete.
public ArrayList<Tweet> getTweets(String Account, int page) {
String accountUrl = "http://search.twitter.com/search.json?q=#"
+ Account + "&rpp=100&page=" + page;
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(accountUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try{
responseBody = client.execute(get, responseHandler);
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
// parse response, return arraylist
}catch(Exception ex) {
ex.printStackTrace();
}
}

Related

Retrieving image link after upload fails

I am trying to create a image upload module Using Imgur API
I have just got Client ID and Client Secret after registration. When it comes to the implementation and testing, it fails and gives the following response in the logcat
The Logcat response
{"data":{"error":"We're really sorry, but
anonymous uploading in your country has
been disabled. Please <a href=\"\/register\">register
for an account<\/a> and try uploading again.","request":"\/3\/upload.json","method":"POST"}
,"success":false,"status":400}
The below is my code
public String uploadToImgur(File uploadFile) {
DefaultHttpClient defaulthttpclient;
HttpPost httppost;
MultipartEntity multipartentity;
String path = uploadFile.getAbsolutePath().toString();
String s;
defaulthttpclient = new DefaultHttpClient();
String targetURL = "https://api.imgur.com/3/upload.json";
String apikey = "client_secret";
httppost = new HttpPost(targetURL);
httppost.setHeader("User-Agent", USER_AGENT);
httppost.addHeader("Authorization", "Client-ID {client)_id}");
multipartentity = new MultipartEntity();
s = path.substring(1 + path.lastIndexOf("."));
if (s.lastIndexOf("jpg") >= 0)
{
s = "jpeg";
}
try
{
multipartentity.addPart("image", new FileBody(new File(path), (new StringBuilder("image/")).append(s).toString()));
multipartentity.addPart("key", new StringBody(apikey));
httppost.setEntity(multipartentity);
String s1 = EntityUtils.toString(defaulthttpclient.execute(httppost).getEntity());
Log.d("outpur" , s1);
if (s1.lastIndexOf("<original>") >= 0 && s1.indexOf("</original>") >= 0)
{
return (new StringBuilder("[img]")).append(s1.substring(10 + s1.lastIndexOf("<original>"), s1.indexOf("</original>"))).append("[/img]").toString();
}
}
catch (Exception exception)
{
return "ERRor";
}
return "Error";
}
Would you please tell me what is the better way to enhance the upload module ?
Registration and sending client id is not good enough for non anonymous uploads. The documentation tells you to use oAuth and get a token that needs to be passed for such requests.
Authentication
The API requires each client to use OAuth 2 authentication. This means you'll have to register your application, and generate an access_code if you'd like to log in as a user.
For public read-only and anonymous resources, such as getting image info, looking up user comments, etc. all you need to do is send an authorization header with your client_id in your requests. This also works if you'd like to upload images anonymously (without the image being tied to an account), or if you'd like to create an anonymous album. This lets us know which application is accessing the API.
Authorization: Client-ID YOUR_CLIENT_ID
For accessing a user's account, please visit the OAuth2 section of the docs

Android & C# Web API - Using Google OAuth2 to log-in to Web API from Android app

Background:
I've got a C# website that requires OAuth Google log-in to access it's pages.
I also have an Android App where I want to access this Web API's pages (with HttpGet-requests and use the returned JSON). I did indeed make an OAuth Google log-in in my Android App, but I need to somehow use that to log-in on the Web API.
I used to have a POST on my C# website that required an AntiForgeryToken to log-in. Because these AntiForgeryTokens only exists very very short (Session-based and changes whenever another page is opened, even the same page in the same browser), I was forced to find a different way. (Because I tried to send a HttpPost in my Android App to log-in with an AntiForgeryToken that I received as a response in the last HttpGet-request, but this token just keeps changing non-stop and caused a no-match in my HttpPost response..)
Current:
Instead I made a new POST-method in my C# web project that doesn't require this [ValidateAntiForgeryToken]. I've also made a System.Web.Security.Role for the Web API pages, and in my API Controllers I've added [Authorize(Role = "web_api")].
When I tested this on my browser:
I removed all Cookies I have in my FireFox browser
I start a Private (Incognito) Window
And used the plug-in RESTClient to make the following POST:
URL: http://localhost:54408/Account/ApiLogin
Headers: Content-Type: application/x-www-form-urlencoded
Body: provider=Google&returnUrl=/Cart/Bestellen
It works with the following response:
When I try to go to this same POST on my Android app however (using the AsyncTask POST-method at the bottom of this page), I get an Error 400 (OAuth2 Error)!!1 in my response.
So, my question: How could I use this new POST that doesn't require any AntiForgeryToken to log-in with an OAuth Google Log-in on my Android App.
Or should I use a completely different approach to log-in with an OAuth Google account on my C# Web API, from within my Android app? (Could I send the OAuth user data from the separate Google log-in in the Android app itself through a different POST? Can I produce this GoogleAccountsLocal_session cookie that is somehow created after the POST-request myself in my Android App to use and put in the HttpClient? So I can get the same response as with the RESTClient POST-request above; if this is indeed the needed cookie to make it work?)
TL;DR: How to log-in to an OAuth2 Google secured C# Web API from within an Android App (so I can send the Web API HttpGet-requests and get JSON returned), without using AntiForgeryTokens whatsoever?
Thanks in advance for the responses.
Android POST class:
public class TaskPostAPI extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls){
String response = "";
for(String url : urls){
InputStream content = null;
BufferedReader buffer = null;
try{
// Get the baseUrl from the given url
URL u = new URL(url);
String baseUrl = u.getProtocol() + "://" + u.getHost();
HttpPost post = new HttpPost(url);
// Add the default Content-type to the Header
post.addHeader("Content-type", "application/x-www-form-urlencoded");
// POST-request requires provider and returnUrl
List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(2);
nvPairs.add(new BasicNameValuePair("provider", "Google"));
nvPairs.add(new BasicNameValuePair("returnUrl", baseUrl));
post.setEntity(new UrlEncodedFormEntity(nvPairs));
// Send the POST-request
HttpResponse execute = MainActivity.HttpClient.execute(post);
// Get the response of the POST-request
content = execute.getEntity().getContent();
buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while((s = buffer.readLine()) != null)
response += s;
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
try{
if(content != null)
content.close();
if(buffer != null)
buffer.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
return response;
}
}

Get Facebook Pages Events using graph Api

I am trying to fetch facebook events from a pages profile using facebook graph api.
The method i was using is like below
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/oauth/access_token?client_id="+APP_ID+"&client_secret="+APP_SECRET+"&grant_type=client_credentials");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String access_token = client.execute(get, responseHandler);
String uri = "https://graph.facebook.com/PageName/events?"+access_token.replace("|","%7C");
get = new HttpGet(uri);
String responseBody = client.execute(get, responseHandler);
in which APP_ID, APP_SECRET and PageName i am replacing with my details.
There is no issue as its working and i am getting the response also from Facebook as a json array which includes name,start_time,end_time,timezone,location,id of the events, but there is no event description.
How to fix this?
By default you don't get event description but you can add the same in using fields along with other information you require and retrieve more detailed listing. So you need to change your uri to
String uri = "https://graph.facebook.com/PageName/events?fields=name,start_time,timezone,location,description"+access_token.replace("|","%7C");
To retrieve the required information.
Use the Event ID you get in the response, and use it to get each and every detail of that event from:
"https://graph.facebook.com/EVENT_ID"

Website login and keep session cookies

I am trying to scrape some content form a website but you must be logged in order to view specific content. I want make a login using user id & password and keep session cookies on: m.amway.com i tried using Jsoup.... however after using the code below i realize that Jsoup cannot read javascript which is what the website is based on....
Does anyone have a method i could use to login, keep session cookie, and scrape content, using something other than Jsoup? Thanks in advance.
public String Jlogin(String User, String Pass) throws Exception{
String title = "didnt work";
Response logRes = Jsoup.connect(AmwayURL)
.data("userid", User)
.data("userpswd", Pass)
.method(Method.POST)
.execute();
// get all cookies
Map<String, String> cookies = logRes.cookies();
Document doc1 = logRes.parse();
String sessionId = logRes.cookie("JSESSIONID");
Document doc2 = Jsoup
.connect("https://m.amway.com/business/volume/pvbv/inquiry.ashx")
.cookie("jsessionid", sessionId).get();
System.out.println(doc2);
title = doc2.toString() + "................." + sessionId;
return title;
}
You can use a much larger API called HttpClient.
has the following classes:
- HttpGet
- HttpPost
- HttpEntity
- HttpResponse
HttpResponse reads Javascript from any page, as follows:
EntityUtils.toString(HttpResponse.getEntity());
for more details on how to use the API, check this link (Extremly helps):
http://www.codeblues.in/blog/?p=5

Unable to get expected response for Facebook photos from an album

I am new to Facebook API. Trying the FQL Query from the Graph API for the first time using this link.
I am trying to get photos from the album with the album id. When I request using Facebook object with https://graph.facebook.com/10150146071791729/photos&access_token=ACCESS_TOKEN URL, I am getting the following response (before parsing to JSON object). {"id":"https://graph.facebook.com/10150146071791729/photos","shares":2}. And I confirmed it by printing the length of the JSON object after parsing, which is 2. When I copy and paste the same URL in the web browser, I am getting the expected response (the response in FQL Query I got). Here is my code.
public void onComplete(Bundle values) {
String token = facebook.getAccessToken();
System.out.println("Token: " + token);
try {
String response = facebook.request("https://graph.facebook.com/10150146071791729/photos&access_token=ACCESS_TOKEN");
System.out.println("response :"+response);
JSONObject obj = Util.parseJson(response);
System.out.println("obj length : " + obj.length());
Iterator iterator = obj.keys();
while(iterator.hasNext()){
String s = (String)iterator.next();
System.out.println(""+s+" : "+obj.getString(s));
}
} catch (Throwable e) {
e.printStackTrace();
}
}
Note: I got access token from the FQL Query which is used in the URL. And I did not wrote any session (login/logout) logic as it is a test project.
Your request is wrong. It should be
"https://graph.facebook.com/10150146071791729/photos?access_token=ACCESS_TOKEN"
Replace the '&' after the photos with a '?'.
Two more things, you're making a Graph API query, not an FQL one.
Second, NEVER post your access tokens publicly. If I wanted to, I can now use your access token to edit your facebook information.
EDIT: When you use the Android Facebook SDK, you do not need to use the full graph path. Instead, use
facebook.request("10150146071791729/photos")
You do not need to add the access token as the Facebook object already has it. Hope this helps.
Because not much code has been provided except for the most relevant one, let me give you a couple of ways you can access Photos from an Album
FIRST METHOD (IF your wish to use the complete URL to make the request)
String URL = "https://graph.facebook.com/" + YOUR_ALBUM_ID
+ "/photos&access_token="
+ Utility.mFacebook.getAccessToken() + "?limit=10";
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String queryPhotos = EntityUtils.toString(rp.getEntity());
Log.e("PHOTOS RESULT", queryPhotos);
}
} catch (Exception e) {
e.printStackTrace();
}
SECOND METHOD (Without using the complete URL as #Vinay Shenoy mentioned earlier)
try {
Bundle paramUserInfo = new Bundle();
paramUserInfo.putString(Facebook.TOKEN, Utility.mFacebook.getAccessToken());
String resultPhotos = Utility.mFacebook.request("YOUR_ALBUM_ID/photos", paramUserInfo, "GET");
Log.e("PHOTOS", resultPhotos);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
On a personal note, I follow the first method almost entirely through my application. It lets me using the Paging for endless ListViews
That being said, when I need some quick data in between somewhere, I do rely on the second method. Both of them work and I hope either (or both) of them helps you.

Categories

Resources