Using Twitter Fabric to retrieve my own account tweets - android

I'm currently using twitter fabric framework and trying to retrieve the list of my own account tweets. I tried searching online to no avail. The example in the document shows how to display a tweet based on tweetID. I do not want that. I do understand that REST client makes a http connection with the supplied variables and to retrieve the JSON results back to parse and etc.
This are my current codes which upon successful login it will display another activity which i want my tweets to be shown here.
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
token = authToken.token;
secret = authToken.secret;
Log.i("token",token);
Log.i("secret",secret);
successNewPage();
}
I have also passed the token and secret key over to the next activity using intent
public void successNewPage(){
Intent intent = new Intent(this, LoginSuccess.class);
intent.putExtra("token",token);
intent.putExtra("secret", secret);
startActivity(intent);
}
On the new activity class, i followed their documentation and came out with this,
TwitterAuthConfig authConfig = new TwitterAuthConfig("consumerKey", "consumerSecret");
Fabric.with(this, new TwitterCore(authConfig), new TweetUi());
TwitterCore.getInstance().logInGuest(new Callback() {
public void success(Result appSessionResult) {
//Do the rest API HERE
Bundle extras = getIntent().getExtras();
String bearerToken = extras.getString("token");
try {
fetchTimelineTweet(bearerToken);
} catch (IOException e) {
e.printStackTrace();
}
}
public void failure(TwitterException e) {
Toast.makeText(getApplicationContext(), "Failure =)",
Toast.LENGTH_LONG).show();
}
});
}
And the retrieve of tweets would be:
// Fetches the first tweet from a given user's timeline
private static String fetchTimelineTweet(String endPointUrl)
throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "anyApplication");
connection.setRequestProperty("Authorization", "Bearer " + endPointUrl);
connection.setUseCaches(false);
String res = readResponse(connection);
Log.i("Response", res);
return new String();
} catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
What i get in my log is:
380-380/com.example.john.fabric W/System.errīš• java.io.IOException: Invalid endpoint URL specified.
Is my url wrong? Or is the token which I set in the endpointURL wrong too?
Any advice would be greatly appreciated. Thanks!

That should be the case, the message was thrown by the fetchTimelineTweet function. That should be caused by this line : URL url = new URL(endPointUrl); which tells that the endPointUrl causes MalformedURLException
EDIT :
According to the Twitter Dev Page, you should put this as endpointURL : https://dev.twitter.com/rest/reference/get/statuses/user_timeline and pass the user screenname as parameter.
EDIT 2 :
I think your code should be like this :
private static String fetchTimelineTweet(String endPointUrl, String token) // this line
throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "anyApplication");
connection.setRequestProperty("Authorization", "Bearer " + token); // this line
connection.setUseCaches(false);
String res = readResponse(connection);
Log.i("Response", res);
return new String();
} catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}

Related

Content-Length on http GET causing IIS to timeout?

So we're encountering a scenario where our Android clients are receiving a redirect from the server (following a POST -- Post/Redirect/Get) and Android is removing the body for the conversion to GET but seems to be leaving the Content-Length header in the GET request. I've verified that the request isn't making it into the web application (by placing a delegating handler that fires before a controller is selected). We also verified via cURL that if the content-length is removed from the request, the request goes through just fine.
So we're trying to find a solution on either front:
a) how do we stop android from sending that header? or
b) how do we tell IIS to allow or strip out the content-length header so that the request can get through?
UPDATE:
Requested java code that makes the call, as requested...
OutputStream postOut = null;
HttpURLConnection connection = null;
try {
URL url = new URL("<<url here>>");
connection = (HttpURLConnection) url.openConnection();
final String method = "POST";
final String data = "name=frank";
final String contentType = "application/x-www-form-urlencoded";
connection.setDoInput(true);
connection.setRequestProperty("Accept", contentType);
connection.setRequestProperty("Connection", "Close");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestMethod(method);
connection.setConnectTimeout(0);
connection.setReadTimeout(0);
connection.setUseCaches(false);
connection.setDefaultUseCaches(false);
connection.setChunkedStreamingMode(0);
if (method.equals("POST")) {
byte[] bits = data.getBytes();
connection.addRequestProperty("Content-Length", "" + bits.length);
connection.setDoOutput(true);
dumpHeaders(connection.getRequestProperties());
postOut = connection.getOutputStream();
if (postOut != null)
{
postOut.write(bits, 0, bits.length);
postOut.flush();
postOut.close();
postOut = null;
}
} else {
dumpHeaders(connection.getRequestProperties());
}
int httpStatus = connection.getResponseCode();
if (httpStatus / 100 > 3) {
Log.d("TEST", readResponse(connection.getErrorStream(), connection));
} else {
Log.d("TEST", readResponse(connection.getInputStream(), connection));
}
String finalUrl = connection.getURL().toExternalForm();
Log.d("TEST", "HTTP Status: " + httpStatus + ", URL: " + finalUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
if (connection.getErrorStream() != null) {
Log.d("TEST", readResponse(connection.getErrorStream(), connection));
} else {
Log.d("TEST", e.getMessage());
}
}
if (connection != null) {
connection.disconnect();
}

Properly implement AccountManager, oauth-2 and expired token

I am struggling with Account manager and OAuth-2 for some time, I have already implemented AccountManager (with service and account authenticator), Login activity with webview, etc.
I implemented all oauth-2 flow, when user enters its credentials on webview, and I save access token as AccountManager password.
The last thing I do now know how correctly implement the flow when I do an http-request to server, and its responce is Json with
{"message":"access_token_is_expired","error":true....}
so I should read this responce, analize it and do another request with resresh token to get another access token.
How correctly implements this? Where? In what class?
May be my Authenticator.getAuthToken method should be improved?
this is the code:
#Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
String authTokenType, Bundle loginOptions) throws NetworkErrorException {
Log.v(TAG, "getAuthToken()");
if (!authTokenType.equals(Const.AUTHTOKEN_TYPE)) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
return result;
}
final AccountManager am = AccountManager.get(mContext);
final String auth_token = am.getPassword(account);
if (auth_token != null) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, Const.ACCOUNT_TYPE);
result.putString(AccountManager.KEY_AUTHTOKEN, auth_token);
return result;
}
final Intent intent = new Intent(mContext, LoginActivity.class);
intent.putExtra(Const.KEY_SERVER, am.getUserData(account, Const.KEY_SERVER));
//intent.putExtra(LoginActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
#Override
protected JSONObject doInBackground(Void... params) {
InputStream is = null;
try {
String url = "...";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String urlParameters = "access_token=" + mToken;
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
conn.connect();
int response_code = conn.getResponseCode();
is = conn.getInputStream();
String str_response = NetworkUtilities.readStreamToString(is, 500);
JSONObject response = new JSONObject(str_response);
return response;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
I did a huge work to understand this, but I failure.
After several days and because of luck of information in the Net, I read codes on github and did some researches. In order to help somebody like me:
The expired token can be reasked in getAuthToken method above, but adding in Bundle (loginOptions) information that it should be reasked from server (for example, as "forceReauth" = true )
I check this parameter inside method and ask the method (2nd peace of code above), otherwize I use usual flow.
The second important thing - one row of code, that I see in here
Why is AccountAuthenticator#getAuthToken() not called?
God bless Tom G (I cannot add him a vote, because of luck of my reputation). The line of code
with invalidateAuthToken BEFORE getAuthToken did everything for me. Add him a vote for me, if you found this useful.

Android App and Http Requests

I'm currently trying to send an http request from an android app to google-app-engine, this request should be received by the server who will use the parameters passed in the URL to add a new item to the datastore.
I wrote this code:
private class AsyncConnection extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
// creating the url
URL url = new URL(params[0]);
// opening the connection
URLConnection connection;
connection = url.openConnection();
// get data about the connection
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
// connection was properly established
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream input = httpConnection.getInputStream();
return input.toString();
} else {
Log.d("CONNECTION", "connection not HTTP_OK");
}
} catch (MalformedURLException e) {
Log.d("SMARTGAN", "MalformedURLException" ,e);
} catch (IOException e) {
Log.d("SMARTGAN", "IOException" ,e);
} catch (Exception e) {
Log.d("SMARTGAN", "Exception" ,e);
} finally { }
return null;
}
}
but when I try to execute it I don't see any new item in the datastore.
The URL itself and the code on the server are fine, when I tried and sent the URL using it worked. I don't see any error message of "connection not ok" message in the log.
Mostly probably could be with hostname, have tried this solution How to make http post from android to google app engine server?
Also refer to https://developers.google.com/appengine/docs/java/tools/devserver#Command_Line_Arguments

Your browser sent a request that this server could not understand HttpsURLConnection

I am making a login app to retreive some information from the link that appears in the code. My problem is that I'm getting a "400 Bad request. Your browser sent a request that this server could not understand. [...] Server at idp.tut.fi Port 443" in the Log file.
Besides, that link handles RC4_128 with SHA1 for authentication and RSA for key exchange but don't really know where I can apply those protocols in my code.
Thanks for your help!
This is my code:
public class POPLogin extends Activity {
private EditText usr, pass;
private Button submitButton;
private CharSequence notify;
private String res, resp;
private final String link = "https://idp.tut.fi/idp/Authn/UserPassword";
private URL url;
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poplogin);
usr = ((EditText) findViewById(R.id.usernameField));
pass = ((EditText) findViewById(R.id.passwordField));
submitButton = (Button) findViewById(R.id.submitButton);
submitButton.getBackground().setColorFilter(new LightingColorFilter(0x00FFB90F, 0xFFAA0000));
/*
* This method controls the login button so that the correct
* information is sent to the server.
*/
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isNetworkAvailable(getApplicationContext())) { // If there is an Internet connection available
/*
* A new thread is created from the main one
* to separate the login process (AsyncTask, https operations).
*/
new Thread(new Runnable() {
public void run() {
try {
url = new URL(link);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// Create the SSL Connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
// SSL Authentication
String userpass = usr.getText().toString() + ":" + pass.getText().toString();
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);
Log.i("NOTIFICATION", "All SSL parameters set");
// Set timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true); // Flag indicating this connection is used for output (POST)
conn.connect();
Log.i("NOTIFICATION", "Connection request sent");
// Check HTTP Response Code
int status = conn.getResponseCode();
InputStream is;
if (status >= 400 ) {
is = conn.getErrorStream();
} else {
is = conn.getInputStream();
}
Log.i("NOTIFICATION", "HTTP Code Checked");
// Receives the answer
resp = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while((res = rd.readLine()) != null) {
resp += res;
}
Log.i("NOTIFICATION", "Answer received");
Log.i("CODE", resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} else {
notify = "Internet Connection not available";
}
if(notify != null) {
Toast toast = Toast.makeText(getApplicationContext(), notify, Toast.LENGTH_SHORT);
toast.show();
notify = null;
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.poplogin, menu);
return true;
}
}
If you got an HTTP error code it is proof that your HTTPS and therefore SSL setup is working perfectly.
The problem is in the data you're sending. It looks like you need to use a java.net.Authenticator rather than try to do it by hand.

How to implement C2DM in android?

I am searching about how to send notification using C2DM. I found something and using that I am able to generate Registration Key as well as an Authentication Key.
But after that in ServerSimulator class (sever side code) I got 401 Error (401 Unauthorized).Now I passed Username and Password manually, which I synchronized in my Android device. I get same error as before.
I face this problem when I click on send message button..
I am stuck on this query. Has anyone managed to do this?
public class ServerSimulator extends Activity
{
private SharedPreferences prefManager;
private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
// Registration is currently hardcoded
private final static String YOUR_REGISTRATION_STRING = "APA91bFkxmtIj5XiBU-Cze64s0gXNb7OmiWWZg-qLKibpLsVXaWq1X7hoRV9Ld9COYXirZAgkYegZBdBfUGt3lgtuhNJopvHB0KJ5ZyJ6Kt_HYRrZhgdJ1Y";
private SharedPreferences prefs;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prefManager = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem_user:
Intent intent = new Intent(this, UserPreferences.class);
startActivity(intent);
break;
default:
break;
}
return false;
}
public void getAuthentification(View view) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email","myEmail id")));
nameValuePairs.add(new BasicNameValuePair("Passwd","my password")));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source","Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
Editor edit = prefManager.edit();
edit.putString(AUTH, line.substring(5));
edit.commit();
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void showAuthentification(View view) {
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
public void sendMessage(View view) {
try {
Log.e("Tag", "Started");
String auth_key = prefManager.getString(AUTH, "n/a");
// Send a sync message to this Android device.
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(YOUR_REGISTRATION_STRING);
// if (delayWhileIdle) {
// postDataBuilder.append("&").append(PARAM_DELAY_WHILE_IDLE)
// .append("=1");
// }
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode("Lars war hier", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ auth_key);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
Log.e("Tag", String.valueOf(responseCode));
// Validate the response code
if (responseCode == 401 || responseCode == 403) {
// The token is too old - return false to retry later, will
// fetch the token
// from DB. This happens if the password is changed or token
// expires. Either admin
// is updating the token, or Update-Client-Auth was received by
// another server,
// and next retry will get the good one from database.
Log.e("C2DM", "Unauthorized - need token");
}
// Check for updated token header
String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH);
if (updatedAuthToken != null && !auth_key.equals(updatedAuthToken)) {
Log.i("C2DM",
"Got updated auth token from datamessaging servers: "
+ updatedAuthToken);
Editor edit = prefManager.edit();
edit.putString(AUTH, updatedAuthToken);
}
String responseLine = new BufferedReader(new InputStreamReader(
conn.getInputStream())).readLine();
// NOTE: You *MUST* use exponential backoff if you receive a 503
// response code.
// Since App Engine's task queue mechanism automatically does this
// for tasks that
// return non-success error codes, this is not explicitly
// implemented here.
// If we weren't using App Engine, we'd need to manually implement
// this.
if (responseLine == null || responseLine.equals("")) {
Log.i("C2DM", "Got " + responseCode
+ " response from Google AC2DM endpoint.");
throw new IOException(
"Got empty response from Google AC2DM endpoint.");
}
String[] responseParts = responseLine.split("=", 2);
if (responseParts.length != 2) {
Log.e("C2DM", "Invalid message from google: " + responseCode
+ " " + responseLine);
throw new IOException("Invalid response from Google "
+ responseCode + " " + responseLine);
}
if (responseParts[0].equals("id")) {
Log.i("Tag", "Successfully sent data message to device: "
+ responseLine);
}
if (responseParts[0].equals("Error")) {
String err = responseParts[1];
Log.w("C2DM",
"Got error response from Google datamessaging endpoint: "
+ err);
// No retry.
throw new IOException(err);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
You are currently implementing C2DM in an older way. The way you are doing offers a lot of customizability, but not many people need that kind of customizability. With the new Google Plugin 2.4 Beta they have actually started integrating it all in, and it's pretty nice.
I'd highly recommend you watch the Google IO Android + AppEngine. They show how to integrate Android, AppEngine, and C2DM together really really simply. You can create something they call an "AppEngine Connected Android Project". So instead of making a ServerSimulator, you'd be actually working with a real server that can all be setup for free.
http://www.youtube.com/watch?v=M7SxNNC429U
If you wanted to move to another server, you'd have to re-write the server-side code, and then just change the URL that it's posting to. Pretty simple. I'd highly recommend checking out this example and working with the stock code, as it gives you something working right off the bat to play with:
FYI, there is currently a bug in the code (as it is in beta atm) when it comes to registering to a real hosted appengine server (everything works fine locally). It tries to send an expired registration token. I've been in contact with the google developers and they provided a fix for me. Let me know if you get to the point where you need it.

Categories

Resources