Tumblr Xauth Android - 400错误请求错误

时间:2012-01-24 22:02:43

标签: android tumblr xauth

我正在尝试与Tumblr一起使用Xuath。我已经通过电子邮件向Tumblr支持团队发送电子邮件,以便为我的应用启用Xuath,他们有义务。但是,在尝试检索用户密钥和密钥时,我不断收到“400:错误请求”错误。我找不到调试错误请求的方法。

以下是代码:( 注意 - 此代码是从网络上提供的代码段开发的

private final String CONSUMER_KEY = "mdMFLrprZGnRw4XO736GXcXP8huxaxTT5z1nlxDK38GbyWlW38";
private final String CONSUMER_SECRET = "VOpRNqKSLjhD3bR8vw4MorXgGc7lkT2FtBZr9xDchA5AvfscUI";

private final String ACCESS_URL = "https://www.tumblr.com/oauth/access_token";
private final String XAUTH_MODE = "client_auth";
private final String SIGNATURE_METHOD = "HMAC-SHA1";
private final String OAUTH_VERSION = "1.0";


private EditText mEmailAddress;
private EditText mPassword;
private Button mLogInButton;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.tumblr_layout);

    mEmailAddress = (EditText) findViewById(R.id.email_tumblr);
    mPassword = (EditText) findViewById(R.id.passowrd_tumblr);
    mLogInButton =  (Button) findViewById(R.id.tumblr_login_button);

    mLogInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String email = mEmailAddress.getText().toString();
            String password= mPassword.getText().toString();



            String oauth_nonce = a64BitRandomString();
            String oauth_timestamp = getTimeStamp();


            String signatureBaseString =
                    "POST"
                    + "&"
                    + URLEncoder.encode(ACCESS_URL)
                    + "&"
                    + URLEncoder.encode("oauth_consumer_key=" + URLEncoder.encode(CONSUMER_KEY))
                    + URLEncoder.encode("&" + "oauth_nonce=" + URLEncoder.encode(oauth_nonce))
                    + URLEncoder.encode("&" + "oauth_signature_method=" + URLEncoder.encode(SIGNATURE_METHOD))
                    + URLEncoder.encode("&" + "oauth_timestamp=" + URLEncoder.encode(oauth_timestamp))
                    + URLEncoder.encode("&" + "oauth_version=" + URLEncoder.encode(OAUTH_VERSION))
                    + URLEncoder.encode("&" + "x_auth_username=" + URLEncoder.encode(email))
                    + URLEncoder.encode("&" + "x_auth_password=" + URLEncoder.encode(password))
                    + URLEncoder.encode("&" + "x_auth_mode=" + URLEncoder.encode(XAUTH_MODE));


            String oauth_signature= getSignature(signatureBaseString, "HmacSHA1",
                    CONSUMER_SECRET+"&");

            try {
                String headerValue = "OAuth " +
                        "oauth_nonce=\""+oauth_nonce+"\"," +
                        "oauth_signature_method=\""+SIGNATURE_METHOD+"\"," +
                        "oauth_timestamp=\""+oauth_timestamp+"\"," +
                        "oauth_consumer_key=\""+CONSUMER_KEY+"\"," +
                        "oauth_signature=\""+URLEncoder.encode(oauth_signature,"UTF-8")+"\"," +
                        "oauth_version=\""+OAUTH_VERSION+"\"";

                HttpPost httppost = new HttpPost(ACCESS_URL
                        +"?x_auth_username="+URLEncoder.encode(email)
                        +"&x_auth_password="+URLEncoder.encode(password)
                        +"&x_auth_mode="+URLEncoder.encode(XAUTH_MODE));    

                httppost.setHeader("Host","https://www.tumblr.com");
                httppost.setHeader("Content-Type","application/x-www-form-urlencoded");
                httppost.setHeader("Authorization",headerValue);


                // Execute HTTP Post Request
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost); // **I get the 401 error here**
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String jString= EntityUtils.toString(entity);
                Log.d("TUMBLR - Value(s):", jString);
                }

            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

}

private String a64BitRandomString() {
    StringBuffer sb = new StringBuffer();
    Random generator = new Random();

    for (int i = 0; i < 32; i++) {
        Integer r = generator.nextInt();
        if (r < 0) {
            r = r * -1;
        }
        r = r % 16;

        sb.append(Integer.toHexString(r));
    }

    return sb.toString();
}


private String getTimeStamp(){
    long seconds = (long) (System.currentTimeMillis()/1000.0);
    String secondsString = String.valueOf(seconds);
    return secondsString;
}

private String getSignature(String base, String mode, String secret) {
    String signature = null;


    SecretKeySpec key;
    try {
        key = new SecretKeySpec((secret).getBytes("UTF-8"), mode);

        Mac mac = Mac.getInstance(mode);
        mac.init(key);

        byte[] bytes = mac.doFinal(base.getBytes("UTF-8"));

        signature = new String(Base64.encode(bytes,Base64.NO_WRAP));
    }
    catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return signature;
}

我知道在这里找出确切的错误是非常困难的。但是,如果有人能提出建议或指出我正确的方向,我会很高兴。

String headerValue 具有以下值:

的OAuth oauth_nonce = “8d0e6e03ae2424260ddd647d5afba70d”,oauth_signature_method = “HMAC-SHA1”,oauth_timestamp = “1327434351943”,oauth_consumer_key = “mdMFLrprZGnRw4XO736GXcXP8huxaxTT5z1nlxDK38GbyWlW38”,oauth_signature = “cYNStrfA%2F2lTaGKL8pxWHpzSq9w%3D”,oauth_version = “1.0”

所以,它似乎是正确的格式。将换行符添加到字符串中会有帮助吗?

2 个答案:

答案 0 :(得分:1)

在将我的头发分开几天之后,事实证明我在HTTP帖子中发送了太多信息(因此,错误的请求错误被抛回了我)。所有必要的是以下一组参数:

x_auth_username(用户的电子邮件地址),x_auth_password和x_auth_mode = client_auth

另外,我应该使用强大的Oauth Library函数,而不是尝试使用我有限的知识编写自己的函数。在我的辩护中,文档从来都不是很清楚。非常好的一课 - 关于重新编写代码和使用常识。对于那些可能想知道TUMBLR是否存在合法的Java客户端的人 - 这里是github链接:https://github.com/nsheridan/tumblr-java。我向你们保证,这是我遇到过的最好的Tumblr代码。

答案 1 :(得分:0)

经过大量搜索后,在Twitter上找到了以下代码 -

            // replace with your username and password
            String password = “passwd”;
            String userName = “test@test.com”;

            HttpPost httppost = new HttpPost("https://www.tumblr.com/oauth/access_token");
            CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(
                    CONSUMER_KEY, CONSUMER_SECRET);     

            List<BasicNameValuePair> reqParams = Arrays.asList(
                    new BasicNameValuePair("x_auth_username", userName),
                    new BasicNameValuePair("x_auth_password", password),
                    new BasicNameValuePair("x_auth_mode", "client_auth"));

            AuthToken authToken = null;
            try {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(reqParams, HTTP.UTF_8);
                httppost.setEntity(entity);
                consumer.sign(httppost);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() == HttpStatus.SC_OK) 
                {
                    InputStream data = response.getEntity()
                            .getContent();

                    final char[] buffer = new char[0x10000];
                    StringBuilder out = new StringBuilder();
                    Reader in = new InputStreamReader(data, HTTP.UTF_8);
                    int read;
                    do {
                        read = in.read(buffer, 0, buffer.length);
                        if (read > 0)
                            out.append(buffer, 0, read);
                    } while (read >= 0);
                    in.close();
                    String responseString = out.toString(); 

                    String[] splitResponse = StringUtils.split(responseString, "&");
                    String accessTokenSecret = getParameter(splitResponse, "oauth_token_secret");
                    String accessToken = getParameter(splitResponse, "oauth_token");

                }
            } catch (UnsupportedEncodingException e) {
            } catch (OAuthMessageSignerException e) {
            } catch (OAuthExpectationFailedException e) {
            } catch (OAuthCommunicationException e) {
            } catch (Exception e) {
            }