I need to post a image to Tumblr. I read this http://www.tumblr.com/docs/en/api/v2#auth and I come to know I need to get the user info in order to get the blog name. I used the same code I used for Twitter authetication, changed the URLs and get successfully loaded the Tumblr webview. I used the following code to authenticate and to obtain the users info.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.twitter.imageupload.R;
import com.twitter.imageupload.SecondClass;
import com.twitter.imageupload.TwitterImageUpload;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.http.HttpParameters;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.http.AccessToken;
import twitter4j.http.OAuthAuthorization;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class Tumblr_Web_View extends Activity {
SharedPreferences settings;
public static final String PREFS_NAME = "GREATEST_THINGS";
SharedPreferences.Editor editor;
final String TAG = getClass().getName();
Button cancel_button;
public static String usr_img, log_res, log_id;
private OAuthConsumer consumer;
private OAuthProvider provider;
WebView tumblr_web_view;
String tweet_Sign_in;
static twitter4j.Twitter twitter;
public static String userName;
public static URL twt_img_url;
AccessToken accessToken;
SharedPreferences twtuname_pref;
SharedPreferences userpref;
public static final String USER_PREF = "TWITTER_USER";
SharedPreferences.Editor usereditor;
SharedPreferences twtlogpref;
public static SharedPreferences.Editor twtlogeditor;
public static final String TWTPREF_LOGIN = "LOGIN ID";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.tumblr_web_view);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
tumblr_web_view = (WebView) findViewById(R.id.tumblr_web_view);
twtuname_pref = this.getSharedPreferences("user_pref", 1);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
userpref = getSharedPreferences(USER_PREF, 0);
twtlogpref = getSharedPreferences(TWTPREF_LOGIN, 0);
try {
this.consumer = new CommonsHttpOAuthConsumer(
Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,
Constants.ACCESS_URL, Constants.AUTHORIZE_URL);
} catch (Exception e) {
Log.e(TAG, "Error creating consumer / provider", e);
}
Log.i(TAG, "Starting task to retrieve request token.");
// new OAuthRequestTokenTask(this,consumer,provider).execute();
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer,
Constants.OAUTH_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
// Intent intent = new Intent(Intent.ACTION_VIEW,
// Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |
// Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
// this.startActivity(intent);
tumblr_web_view.loadUrl(url);
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the
* request token). The callback URL will be intercepted here.
*/
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null
&& uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this, consumer, provider, prefs)
.execute(uri);
// finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
@SuppressWarnings("unused")
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,
OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs = prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and
* oauth_token_secret for future API calls.
*/
@Override
protected Void doInBackground(Uri... params) {
Uri uri = params[0];
Log.v("uri >>", uri + "");
String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
consumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
// provider.retrieveAccessToken(consumer, oauth_verifier);
Log.v("getToken", consumer.getToken());
Log.v("getTokenSecret", consumer.getTokenSecret());
Editor uname_editor = twtuname_pref.edit();
uname_editor.putString("token", consumer.getToken());
uname_editor.putString("secret_token",
consumer.getTokenSecret());
uname_editor.putString("login_status", "already_logged");
uname_editor.commit();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"http://api.tumblr.com/v2/user/info");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
System.out.println("Returning value of doInBackground :"
+ stringBuilder.toString());
} catch (ClientProtocolException cpe) {
System.out
.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
}
}
I got the following error.
06-06 23:06:20.084: I/System.out(20264): Returning value of doInBackground :{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}
what I have done wrong?
update: Successfully got the user info now. Got the users blog name.
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
@SuppressWarnings("unused")
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,
OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs = prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and
* oauth_token_secret for future API calls.
*/
@Override
protected Void doInBackground(Uri... params) {
Uri uri = params[0];
Log.v("uri >>", uri + "");
String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
consumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
provider.retrieveAccessToken(consumer, oauth_verifier);
Log.v("getToken", consumer.getToken());
Log.v("getTokenSecret", consumer.getTokenSecret());
Editor uname_editor = twtuname_pref.edit();
uname_editor.putString("token", consumer.getToken());
uname_editor.putString("secret_token",
consumer.getTokenSecret());
uname_editor.putString("login_status", "already_logged");
uname_editor.commit();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"http://api.tumblr.com/v2/user/info");
try {
consumer.sign(httpGet);
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
System.out.println("Returning value of doInBackground :"
+ stringBuilder.toString());
} catch (ClientProtocolException cpe) {
System.out
.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
}
I tried to post a image to the logged in user's blog. Used the following code. But didn't get the response.
try {
HttpClient client = new DefaultHttpClient();
client.getConnectionManager()
.getSchemeRegistry()
.register(
new Scheme("SSLSocketFactory", SSLSocketFactory
.getSocketFactory(), 443));
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000);
HttpResponse response1;
HttpPost post = new HttpPost(
"http://api.tumblr.com/v2/blog/"+username+".tumblr.com/post");
consumer.sign(post);
JSONObject json_obj_val = new JSONObject();
json_obj_val.put("type", "photo");
json_obj_val.put("caption", "test");
json_obj_val.put("source", "http://50.57.227.117/blacksheep/uploaded/Detailed_images/961314275649aladdins.jpg");
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
StringEntity entity_val = new StringEntity(
json_obj_val.toString());
entity_val.setContentEncoding(new BasicHeader(
HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(entity_val);
response1 = client.execute(post);
String response_string = EntityUtils.toString(response1.getEntity());
Log.v("response >>", response_string);
Log.v("response length >>", response_string.length() + "");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.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();
}
Got the following response. what is wrong in the code?
06-11 16:24:46.312: V/response >>(27710): {"meta":{"status":400,"msg":"Bad Request"},"response":{"errors":["Post cannot be empty."]}}
I found the solution. I used the following code and get successfully posted the image to the logged in user's blog.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With