Posting to tumblr in android app using access token and token secret - android

I am trying to post a text on tumblr using the access token. These access token i am getting from web services of my web application. please help on this
Here is my code and It is shows this message after execution "Authentication error: Unable to respond to any of these challenges"
String token = list.get(i).getAccess_token();
String tokenSecret = list.get(i).getAccess_token_secret();
System.out.println("token :"+token);
System.out.println("token secret :"+tokenSecret);
HttpPost hpost = new HttpPost("http://api.tumblr.com/v2/blog/" +list.get(i).getUser_Name()+ ".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "text"));
nameValuePairs.add(new BasicNameValuePair("title", title));
nameValuePairs.add(new BasicNameValuePair("body", body));
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(Tumblr.TUMBLR_CONSUMERKEY, Tumblr.TUMBLR_SECRETKEY);
consumer.setTokenWithSecret(token, tokenSecret);
try {
consumer.sign(hpost);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = null;
try {
resp = client.execute(hpost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Following code working for me:
public class PostToTumblr extends AsyncTask<String, String, String> {
private String userName;
ProgressDialog progressDlg;
int pos;
CommonsHttpOAuthConsumer oAuthConsumer;
CommonsHttpOAuthProvider oAuthprovider;
TumblrUser user;
public PostToTumblr(TumblrUser user) {
this.user= user;
progressDlg = new ProgressDialog(mContext);
progressDlg.setMessage("Posting Message ");
this.userName = user.getName();
oAuthConsumer = new CommonsHttpOAuthConsumer(Const.CONSUMER_KEY,
Const.CONSUMER_SECRET);
oAuthConsumer.setTokenWithSecret(user.getToken(), user.getSecret());
oAuthprovider = new CommonsHttpOAuthProvider(Const.REQUEST_URL,
Const.ACCESS_URL, Const.AUTHORIZE_URL);
oAuthprovider.setOAuth10a(true);
}
protected void onCancelled() {
progressDlg.cancel();
}
protected void onPreExecute() {
super.onPreExecute();
progressDlg.show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDlg.dismiss();
}
#Override
protected String doInBackground(String... params) {
try {
oAuthprovider.retrieveAccessToken(oAuthConsumer, user.getSessionUri().getQueryParameter("oauth_verifier"));
} catch (OAuthMessageSignerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthNotAuthorizedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthExpectationFailedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthCommunicationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = null;
String result = null;
HttpPost hpost = new HttpPost("http://api.tumblr.com/v2/blog/"
+ userName + ".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "photo"));
nameValuePairs.add(new BasicNameValuePair("caption",
"hello final message for testing"));
nameValuePairs.add(new BasicNameValuePair("source",
"http://www.gstatic.com/webp/gallery/1.jpg"));
try {
hpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
oAuthConsumer.sign(hpost);
resp = client.execute(hpost);
result = EntityUtils.toString(resp.getEntity());
Log.v("result >>", result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

Related

Posting image using tumblr

{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}
Tumblr gives above result while posting image.
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = null;
String result = null;
HttpPost hpost = new HttpPost("http://api.tumblr.com/v2/blog/" + username
+".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "photo"));
nameValuePairs.add(new BasicNameValuePair("caption", "hello"));
nameValuePairs.add(new BasicNameValuePair("source", "url_of_the_image"));
String debug = "";
try {
hpost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
consumer.sign(hpost);
resp = client.execute(hpost);
result = EntityUtils.toString(resp.getEntity());
Log.v("result >>", result);
} catch (UnsupportedEncodingException e) {
debug += e.toString();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I need to post the image in tumblr. Give me some solutions.
Have you considered using a third-party library? The Temboo SDK (free account required) includes methods to create Tumblr photo posts either by passing a photo URL or the Base64 encoded content of the photo. Take a look at:
https://www.temboo.com/library/Library/Tumblr/Post/CreatePhotoPostWithURL/ https://www.temboo.com/library/Library/Tumblr/Post/CreatePhotoPostWithImageFile/
Full disclosure -- I work at Temboo.

How to get images from facebook album

I have albumID,I did the following code but not able to get the result (photos).
I think m missing something in facebook.request
try {
//wallAlbumID is variable having album id.
response = facebook.request("me/album."+wallAlbumID+"/photos");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = null;
try {
json = Util.parseJson(response);
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray photos = null;
try {
photos = json.getJSONArray("data");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i =0; i < photos.length(); i++) {
JSONObject a = null;
try {
a = photos.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
looking for code in response.
If you already know your Album ID, you don't have to add me/albums/ to your request. Try this:
response = facebook.request(wallAlbumID+"/photos");

AsyncTask doInBackground returning a nullpointerexception only sometimes

Getting this error:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1027)
Caused by: java.lang.NullPointerException
at com.Wahoo.BrowseListActivity$DownloadSite.doInBackground(BrowseListActivity.java:79)
at com.Wahoo.BrowseListActivity$DownloadSite.doInBackground(BrowseListActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
... 4 more
Here's my AsyncTask...it crashes only for some users at particular times...not sure why. Perhaps they lose their internet connection mid-query? What am I doing wrong here? Here's my code:
private class DownloadSite extends AsyncTask<String, Integer, String> {
private HttpResponse response;
private InputStream in;
private Context context;
private String html;
private ProgressDialog progress;
#Override
protected String doInBackground(String... params) {
in = null;
String url = "aURLGOESHERE_BUTI'MCENSORING" + params[0] + "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
html = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
} catch (Exception e) {
this.publishProgress();
this.cancel(true);
e.printStackTrace();
}
StringBuilder str = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
html = params[0] + str.toString();
return html;
}
#Override
protected void onPreExecute() {
progress = new ProgressDialog(BrowseListActivity.this);
progress.setIndeterminate(true);
progress.setMessage("Loading...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
CharSequence text = "Connection interrupted...please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(getApplicationContext(), text,
duration);
toast.show();
}
#Override
protected void onPostExecute(String html) {
progress.dismiss();
Context context = BrowseListActivity.this;
Intent stopViewer = new Intent(context, StopActivity.class);
stopViewer.setData(Uri.parse(html + ""));
context.startActivity(stopViewer);
}
}
One thing that you are doing wrong is continuing to execute doInBackground after an error that makes it impossible to continue meaningfully. For instance:
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
If this throws an exception, response is going to be null and there's no point in proceeding further. You'll generate a NullPointerException in the next block of code. That won't be fatal, because you are catching all exceptions there. Further on, though, this pattern repeats and you aren't catching all exceptions.
You should exit prematurely, returning null as the String result. Then you can test for a null in onPostExecute and let the user know what happened in a graceful way.

Android - HttpClient execute has a mind of its own - 1 second or 200 seconds

I'm trying to use HttpClient to connect to a php page that logs in and passes back a sessionid and then goes to a new page, using that sessionid and obtains a mySQL datafield associated with that sessionid.
On the first request, HttpClient can take 1.5 seconds, 6 seconds, or 2 minutes. If the first request was slow, subsequence requests seem to be faster, and visaversa.
The HttpClient request occurs when a Button view is clicked
Here's my code:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
name = (TextView)findViewById(R.id.name);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.pass);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(this);
HttpParams params1 = new BasicHttpParams();
params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client = new DefaultHttpClient(params1);
httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Create local HTTP context
}
public void onClick(View v) {
if (v.getId() == R.id.button1) {
//submit.setClickable(false);
String username = user.getText().toString();
String password = pass.getText().toString();
String targetURL = "<<<<LOGIN PHP URL>>>>";
post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("params","params added");
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("entity added","entityadded");
Log.d("preex","PRE EXECUTION");
localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//submit.setText("Logging In...");
new Thread(new Runnable(){
public void run(){
try {
Log.d("pre","pre execute");
response = client.execute(post,localContext);
Log.d("post","post execute");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("response: ",convertStreamToString(input));
getFullName(localContext);
}
}
}).start();}
}
private void getFullName(final HttpContext context){
Log.d("called","called");
String targetURL = "<<<<SESSION CHECKER PHP URL>>>>";
//client1 = new DefaultHttpClient();
post1 = new HttpPost(targetURL);
Log.d("","about to call runable....");
// submit.setText("Obtaining Full Name...");
try {
Log.d("pre","CALLING!");
response = client.execute(post1,context);
Log.d("post","called..");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
//submit.setText("Full Name Obtained!...");
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("response: ",convertStreamToString(input));
outputResponse(input);
}
}
private void outputResponse(final InputStream in) {
name.post(new Runnable(){
public void run(){
String fullname=convertStreamToString(in);
name.setText("Full Name is: "+fullname);
}
});
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Before I set Http version 1.1 it took double the time, but for my application, the speed cannot be unreliable. This is all on a pretty fast WiFi connections -- can you image Edge or 3G speeds??
So what can I optimize?
Thanks everyone:)
EDIT: I did a new test with: http://www.posttestserver.com/ and it happened pretty fast. The urls I'm using currently aren't my final server urls, they are for a different site on a different server -- shared hosting, so could it be that contacting my shared hosting site is just slow and will be compared to my .net server?
Thanks again !

fetch photos from facebook album in android

m trying fetch all photos from perticular album from facebook in android , i am using facebook android sdk to do the task but the problem is , i don't know what url request is required to access the photos inside album ?
https://graph.facebook.com/ALBUM_ID/photos
If it's for a particular person then:
https://graph.facebook.com/me/albums/
And then choose the album id and then use the first call
EDIT
You will also need to give permission while creating Facebook object in the Permission String array also need to add user_photos to be able to load photos
Code Worked for Me.
I have two function - one is to get Album id and anther one is just retrieving all images from that particular album.
First use test() function and then use downloadpic().
public void test()
{
facebook.getAccessToken();
JSONArray albumss=null;
String response = null;
try {
response = facebook.request("me/albums");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = null;
try {
json = Util.parseJson(response);
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray albums = null;
try {
albums = json.getJSONArray("data");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i =0; i < albums.length(); i++) {
JSONObject album = null;
try {
album = albums.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//Here I have selected Profile pic album.
if (album.getString("type").equalsIgnoreCase("profile")) {
// JSONArray al=null;
wallAlbumID = album.getString("id");
// Now you have album id in wallAlbumID(global varible).
Log.d("JSON", wallAlbumID);
break;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now use downloadpic():
void downloadpic( )
{
facebook.getAccessToken();
String response = null;
try {
response = facebook.request(wallAlbumID+"/photos");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = null;
try {
json = Util.parseJson(response);
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray photos = null;
try {
photos = json.getJSONArray("data");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i =0; i < photos.length(); i++) {
JSONObject a = null;
try {
a = photos.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String testing = null;
try {
testing = a.getString("source");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
\
URL value=null;
try {
value=new URL(testing);
//Now you have URL of that particular image use it in your way
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}

Categories

Resources