需要发布的图像的tumblr博客的安卓 [英] Need to post an image to Tumblr blog in android

查看:217
本文介绍了需要发布的图像的tumblr博客的安卓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要发布一个形象的tumblr。我读这 http://www.tumblr.com/docs/en/api/v2#auth,我才知道我需要获得用户信息,以获取博客的名字。我用同样的code我用微博authetication,改变了网址,并获得成功加载的tumblr web视图。我用下面的code认证,并获得了用户的信息。

 进口java.io.BufferedInputStream中;
进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.net.URL;
进口java.net.URLConnection中;
进口的java.util.ArrayList;
进口的java.util.List;

进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.StatusLine;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;
进口org.apache.http.util.EntityUtils;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;

进口com.twitter.imageupload.R;
进口com.twitter.imageupload.SecondClass;
进口com.twitter.imageupload.TwitterImageUpload;

进口oauth.signpost.OAuth;
进口oauth.signpost.OAuthConsumer;
进口oauth.signpost.OAuthProvider;
进口oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
进口oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
进口oauth.signpost.http.HttpParameters;
进口twitter4j.conf.Configuration;
进口twitter4j.conf.ConfigurationBuilder;
进口twitter4j.http.AccessToken;
进口twitter4j.http.OAuthAuthorization;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Context;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.content.Shared preferences.Editor;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.net.Uri;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.os.StrictMode;
。进口的Andr​​oid preference preferenceManager。
进口android.util.Log;
进口android.view.Window;
进口android.webkit.WebView;
进口android.widget.Button;
进口android.widget.Toast;


公共类Tumblr_Web_View延伸活动{
    共享preferences设置;
    公共静态最后弦乐preFS_NAME =GREATEST_THINGS;
    共享preferences.Editor编辑;
    最终的字符串变量=的getClass()的getName()。
    按钮cancel_button;
    公共静态字符串usr_img,log_res,LOG_ID;
    私人OAuthConsumer消费;
    私人OAuthProvider供应商;

    的WebView tumblr_web_view;

    字符串tweet_Sign_in;
    静态twitter4j.Twitter微博;
    公共静态字符串用户名;
    公共静态URL twt_img_url;
    AccessToken accessToken;
    共享preferences twtuname_ preF;

    共享preferences用户preF;
    公共静态最后弦乐USER_ preF =TWITTER_USER;
    共享preferences.Editor usereditor;

    共享preferences twtlog preF;
    公共静态共享preferences.Editor twtlogeditor;
    公共静态最后弦乐TWT preF_LOGIN =登录ID;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        的setContentView(R.layout.tumblr_web_view);
        如果(android.os.Build.VERSION.SDK_INT> 9){

            StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()
                    .permitAll()建立()。
            StrictMode.setThreadPolicy(政策);
        }
        tumblr_web_view =(web视图)findViewById(R.id.tumblr_web_view);
        twtuname_ preF = this.getShared preferences(用户_ preF,1);
        设置= getShared preferences(preFS_NAME,0);
        编辑= settings.edit();
        用户preF = getShared preferences(USER_ preF,0);
        twtlog preF = getShared preferences(TWT preF_LOGIN,0);
        尝试 {
            this.consumer =新CommonsHttpOAuthConsumer(
                    Constants.CONSUMER_KEY,Constants.CONSUMER_SECRET);
            this.provider =新CommonsHttpOAuthProvider(Constants.REQUEST_URL,
                    Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
        }赶上(例外五){
            Log.e(TAG,错误创建消费者/提供者,E);
        }

        Log.i(TAG,启动任务检索请求令牌。);
        //新OAuthRequestTokenTask(这一点,消费者,供应商).execute();
        尝试 {
            Log.i(TAG,从谷歌服务器检索请求令牌);
            最终的字符串URL = provider.retrieveRequestToken(消费者,
                    Constants.OAUTH_CALLBACK_URL);
            Log.i(TAG,啪浏览器在authorize网址:+网址);
            //意向意图=新的意图(Intent.ACTION_VIEW,
            // Uri.parse(URL))setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP。|
            // Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
            // this.startActivity(意向);
            tumblr_web_view.loadUrl(URL);

        }赶上(例外五){
            Log.e(TAG,OAuth的过程中出现错误检索请求令牌,E);
        }
    }

    / **
     *当OAuthRequestTokenTask完成所谓的(用户授权
     *请求令牌)。回调URL将在这里拦截。
     * /
    @覆盖
    公共无效onNewIntent(意向意图){
        super.onNewIntent(意向);
        共享preferences preFS = preferenceManager
                .getDefaultShared preferences(本);
        最后开放的URI = intent.getData();
        如果(URI!= NULL
                &功放;&安培; uri.getScheme()。等于(Constants.OAUTH_CALLBACK_SCHEME)){
            Log.i(TAG,回拨收到:+ URI);
            Log.i(TAG,检索访问令牌);

            新RetrieveAccessTokenTask(这一点,消费者,供应商,preFS)
                    .execute(URI);

            // 完();

        }
    }

    公共类RetrieveAccessTokenTask扩展的AsyncTask<开放的,太虚,太虚> {

        @燮pressWarnings(未使用)
        私人上下文的背景下;
        私人OAuthProvider供应商;
        私人OAuthConsumer消费;
        私人共享preferences preFS;

        公共RetrieveAccessTokenTask(上下文的背景下,OAuthConsumer消费,
                OAuthProvider提供商,共享preferences preFS){
            this.context =背景;
            this.consumer =消费;
            this.provider =提供商;
            这preFS = preFS。
        }

        / **
         *检索oauth_verifier,并存储OAuth的和
         * oauth_token_secret为未来的API调用。
         * /
        @覆盖
        保护无效doInBackground(URI ... PARAMS){
            乌里的uri = PARAMS [0];
            Log.v(URI>>中,URI +);

            字符串oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

            尝试 {
                consumer.setTokenWithSecret(consumer.getToken(),
                        consumer.getTokenSecret());
            // provider.retrieveAccessToken(消费者,oauth_verifier);

                Log.v(为gettoken,consumer.getToken());
                Log.v(getTokenSecret,consumer.getTokenSecret());

                编辑uname_editor = twtuname_ pref.edit();
                uname_editor.putString(令牌,consumer.getToken());

                uname_editor.putString(secret_token
                        consumer.getTokenSecret());
                uname_editor.putString(login_status,already_logged);
                uname_editor.commit();

                HttpClient的HttpClient的=新DefaultHttpClient();
                HTTPGET HTTPGET =新HTTPGET(
                        http://api.tumblr.com/v2/user/info);
                尝试 {

                    HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                    的System.out.println(HTT presponse);
                    InputStream中的InputStream = HTT presponse.getEntity()
                            .getContent();
                    InputStreamReader的InputStreamReader的=新的InputStreamReader(
                            InputStream的);
                    BufferedReader中的BufferedReader =新的BufferedReader(
                            InputStreamReader的);
                    StringBuilder的StringBuilder的=新的StringBuilder();
                    字符串bufferedStrChunk = NULL;
                    而((bufferedStrChunk = bufferedReader.readLine())!= NULL){
                        stringBuilder.append(bufferedStrChunk);
                    }
                    的System.out.println(返回doInBackground的价值:
                            + stringBuilder.toString());
                }赶上(ClientProtocolException CPE){
                    System.out的
                            .println(异常产生的HTT presponse CAZ:
                                    + CPE);
                    cpe.printStackTrace();
                }赶上(IOException异常IOE){
                    System.out的
                            .println(第二异常产生的HTT presponse CAZ:
                                    + IOE);
                    ioe.printStackTrace();
                }

            }赶上(例外五){
                Log.e(TAG的OAuth  - 访问令牌获取错误,E);
            }

            返回null;
        }

    }

}
 

我得到了以下错误。

  06-06 23:06:20.084:我/的System.out(20264):doInBackground的返回值:{元:{状态:401,味精 :未授权},回应:[]}
 

我做了什么错?

更新: 顺利拿到了用户的信息了。得到了用户的博客名称。

 公共类RetrieveAccessTokenTask扩展的AsyncTask<开放的,太虚,太虚> {

            @燮pressWarnings(未使用)
            私人上下文的背景下;
            私人OAuthProvider供应商;
            私人OAuthConsumer消费;
            私人共享preferences preFS;

            公共RetrieveAccessTokenTask(上下文的背景下,OAuthConsumer消费,
                    OAuthProvider提供商,共享preferences preFS){
                this.context =背景;
                this.consumer =消费;
                this.provider =提供商;
                这preFS = preFS。
            }

            / **
             *检索oauth_verifier,并存储OAuth的和
             * oauth_token_secret为未来的API调用。
             * /
            @覆盖
            保护无效doInBackground(URI ... PARAMS){
                乌里的uri = PARAMS [0];
                Log.v(URI>>中,URI +);

                字符串oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

                尝试 {
                    consumer.setTokenWithSecret(consumer.getToken(),
                            consumer.getTokenSecret());
                    provider.retrieveAccessToken(消费者,oauth_verifier);

                    Log.v(为gettoken,consumer.getToken());
                    Log.v(getTokenSecret,consumer.getTokenSecret());

                    编辑uname_editor = twtuname_ pref.edit();
                    uname_editor.putString(令牌,consumer.getToken());

                    uname_editor.putString(secret_token
                            consumer.getTokenSecret());
                    uname_editor.putString(login_status,already_logged);
                    uname_editor.commit();

                    HttpClient的HttpClient的=新DefaultHttpClient();
                    HTTPGET HTTPGET =新HTTPGET(
                            http://api.tumblr.com/v2/user/info);
                    尝试 {
        consumer.sign(HTTPGET);
                        HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                        的System.out.println(HTT presponse);
                        InputStream中的InputStream = HTT presponse.getEntity()
                                .getContent();
                        InputStreamReader的InputStreamReader的=新的InputStreamReader(
                                InputStream的);
                        BufferedReader中的BufferedReader =新的BufferedReader(
                                InputStreamReader的);
                        StringBuilder的StringBuilder的=新的StringBuilder();
                        字符串bufferedStrChunk = NULL;
                        而((bufferedStrChunk = bufferedReader.readLine())!= NULL){
                            stringBuilder.append(bufferedStrChunk);
                        }
                        的System.out.println(返回doInBackground的价值:
                                + stringBuilder.toString());
                    }赶上(ClientProtocolException CPE){
                        System.out的
                                .println(异常产生的HTT presponse CAZ:
                                        + CPE);
                        cpe.printStackTrace();
                    }赶上(IOException异常IOE){
                        System.out的
                                .println(第二异常产生的HTT presponse CAZ:
                                        + IOE);
                        ioe.printStackTrace();
                    }

                }赶上(例外五){
                    Log.e(TAG的OAuth  - 访问令牌获取错误,E);
                }

                返回null;
            }

        }
 

我想发布图像登录的用户的博客。用下面的code。但没有得到回应。

 尝试{
                                HttpClient的客户端=新DefaultHttpClient();
                                client.getConnectionManager()
                                        .getSchemeRegistry()
                                        。寄存器(
                                                新的计划(SSLSocketFactory的,SSLSocketFactory的
                                                        .getSocketFactory(),443));
                                HttpConnectionParams.setConnectionTimeout(client.getParams(),
                                        10000);
                                HTT presponse response1;
                                HttpPost后=新HttpPost(
                                        http://api.tumblr.com/v2/blog/"+username+".tumblr.com/post);
                                consumer.sign(后);
                                JSONObject的json_obj_val =新的JSONObject();
                                json_obj_val.put(类,照片);
                                json_obj_val.put(标题,测试);
                                json_obj_val.put(源,http://50.57.227.117/blacksheep/uploaded/Detailed_images/961314275649aladdins.jpg);

                                    post.setHeader(内容类型,应用/ JSON);
                                post.setHeader(接受,应用/ JSON);
                                StringEntity entity_val =新StringEntity(
                                        json_obj_val.toString());
                                entity_val.setContentEncoding(新BasicHeader(
                                        HTTP.CONTENT_TYPE,应用/ JSON));
                                post.setEntity(entity_val);
                                response1 = client.execute(后);
                                串response_string = EntityUtils.toString(response1.getEntity());
                                Log.v(回应>>中,response_string);
                                Log.v(响应长度GT;>中,response_string.length()+);
                            }赶上(UnsupportedEncodingException E1){
                                // TODO自动生成的catch块
                                e1.printStackTrace();
                            }赶上(ClientProtocolException E1){
                                // TODO自动生成的catch块
                                e1.printStackTrace();
                            }赶上(ParseException的E1){
                                // TODO自动生成的catch块
                                e1.printStackTrace();
                            }赶上(JSONException E1){
                                // TODO自动生成的catch块
                                e1.printStackTrace();
                            }赶上(IOException异常E1){
                                // TODO自动生成的catch块
                                e1.printStackTrace();
                            }赶上(OAuthMessageSignerException E){
                                // TODO自动生成的catch块
                                e.printStackTrace();
                            }赶上(OAuthExpectationFailedException E){
                                // TODO自动生成的catch块
                                e.printStackTrace();
                            }赶上(OAuthCommunicationException E){
                                // TODO自动生成的catch块
                                e.printStackTrace();
                            }
 

得到如下回应。什么是错的,在code?

  06-11 16:24:46.312:V /应答GT;>(27710):{元:{状态:400,味精:坏请求},响应:{错误:后不能为空。]}}
 

解决方案

我找到了解决办法。我用下面的code和获得成功的图像发布到登录用户的博客。

  DefaultHttpClient客户端=新DefaultHttpClient();
HTT presponse RESP = NULL;
字符串结果= NULL;
    HttpPost执行hpost =新HttpPost(http://api.tumblr.com/v2/blog/+用户名+.tumblr.com /后);
                                名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
                      nameValuePairs.add(新BasicNameValuePair(类,照片));
                        nameValuePairs.add(新BasicNameValuePair(标题,你好));
        nameValuePairs.add(新BasicNameValuePair(源,url_of_the_image));


            字符串调试=;
            尝试 {
                hpost.setEntity(新UrlEn codedFormEntity(
                        namevaluepairs中));
                consumer.sign(执行hpost);
                RESP = client.execute(执行hpost);
                结果= EntityUtils.toString(resp.getEntity());
                Log.v(结果>>中,结果);
            }赶上(UnsupportedEncodingException E){
                调试+ = e.toString();
            }赶上(OAuthMessageSignerException E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }赶上(OAuthExpectationFailedException E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }赶上(OAuthCommunicationException E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }赶上(ClientProtocolException E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }赶上(IOException异常E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }
 

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();
            }

这篇关于需要发布的图像的tumblr博客的安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆