Twitter OAuth Rest Api Status Parameter '@' symbol
Asked Answered
K

2

7

I am using twitter rest api which is (https://api.twitter.com/1.1/).

First of all I used signpost library to generate oauth_signature. it is working well.

Upload Status endpoint (https://api.twitter.com/1.1/statuses/upload.json) is working well, but if status parameter contains '@' symbol, that is not working. So here is my code

TwitterStatusesService.java

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;

public interface TwitterStatusesService {
    @POST("/1.1/statuses/update.json")
    Call<ResponseBody> update(@Query("status") String status, @Query("in_reply_to_status_id") String inReplyToStatusId, @Query("lat") Double lat, @Query("long") Double lon, @Query("media_ids") String mediaIds);
}

TwitterStatusesAPIClient.java

import android.util.Log;

import com.twitter.sdk.android.core.TwitterAuthToken;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterSession;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer;
import se.akerfeldt.okhttp.signpost.SigningInterceptor;

public class TwitterStatusesClient {

    private final String TAG = getClass().getSimpleName();

    private static final String BASE_URL = "https://api.twitter.com/";

    private final TwitterStatusesService apiService;

    private static TwitterStatusesClient webServiceClient;

    public static TwitterStatusesClient getInstance() {
        if (webServiceClient == null)
            webServiceClient = new TwitterStatusesClient();
        return webServiceClient;
    }

    private TwitterStatusesClient() {
        private TwitterStatusesClient() {
        OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(TWITTER_KEY, TWITTER_SECRET);

        TwitterSession activeSession = TwitterCore.getInstance().getSessionManager().getActiveSession();
        if (activeSession != null) {
            TwitterAuthToken authToken = activeSession.getAuthToken();
            String token = authToken.token;
            String secret = authToken.secret;
            consumer.setTokenWithSecret(token, secret);
        }

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new SigningInterceptor(consumer))
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .build();

        apiService = retrofit.create(TwitterStatusesService.class);
    }

    public Call<ResponseBody> update(String status, String statusId, Double lat, Double lon, String mediaIds) {
        return apiService.update(status, statusId, lat, lon, mediaIds);
    }
}

calling api client

String status = "@example";
TwitterStatusesClient.getInstance().update(status, null, null, null, null).enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.v(TAG, "onResponse");
            progressDialog.dismiss();
            try {
                if (response.errorBody() != null) {
                    String error = response.errorBody().string();
                    Log.e(TAG, "Error : " + error);
                    ToastUtils.showErrorMessage(getContext(), "Error : " + error);
                    return;
                }

                String body = response.body().string();
                Log.v(TAG, "body : " + body);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.v(TAG, "onFailure");
            t.printStackTrace();
        }
    });

giving error :

{"errors":[{"code":32,"message":"Could not authenticate you."}]}

but, if I will use status variable "just example" instead of "@example" ( specific point is removing @ character ) that is working. only '@' symbol is not working.

EDIT

This is my manually creating OAuth v1.0a signature signing code via retrofit interceptor :

OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request request = chain.request();

                    String method = request.method();
                    String baseUrl = "https://api.twitter.com" + request.url().url().getPath();

                    String oauthToken = "";
                    String oauthTokenSecret = "";

                    TwitterSession activeSession = TwitterCore.getInstance().getSessionManager().getActiveSession();
                    if (activeSession != null) {
                        TwitterAuthToken authToken = activeSession.getAuthToken();
                        oauthToken = authToken.token;
                        oauthTokenSecret = authToken.secret;
                    }

                    String oauthNonce = "TXZScw4M8TG";
                    String oauthSignatureMethod = "HMAC-SHA1";
                    String oauthTimestamp = String.valueOf(System.currentTimeMillis() / 1000);
                    String oauthVersion = "1.0";

                    String parameterString = "";

                    parameterString = OAuthParams.addParam(request, parameterString, "count");
                    parameterString = OAuthParams.addParam(request, parameterString, "id");
                    parameterString = OAuthParams.addParam(request, parameterString, "in_reply_to_status_id");

                    // if any parameter added to parameterString, append '&' character.
                    if (parameterString.length() > 0) {
                        parameterString += "&";
                    }

                    parameterString += "oauth_consumer_key=" + TWITTER_KEY + "&"
                            + "oauth_nonce=" + oauthNonce + "&"
                            + "oauth_signature_method=" + oauthSignatureMethod + "&"
                            + "oauth_timestamp=" + oauthTimestamp + "&"
                            + "oauth_token=" + oauthToken + "&"
                            + "oauth_version=" + oauthVersion;

                    // add status parameter to parameterString.
                    parameterString = OAuthParams.addParam(request, parameterString, "status");

                    Log.d(TAG, "normalizedParameters : " + parameterString);
                    Log.d(TAG, "parameterStringPercent : " + OAuth.percentEncode(parameterString));

                    String signatureBaseString = "";
                    signatureBaseString += OAuth.percentEncode(method) + "&";
                    signatureBaseString += OAuth.percentEncode(baseUrl) + "&";
                    signatureBaseString += OAuth.percentEncode(parameterString);

                    String oauthSignature = OauthSignature.generateSignature(signatureBaseString, TWITTER_SECRET,
                            oauthTokenSecret);

                    String authorization = "OAuth oauth_consumer_key=\"" + TWITTER_KEY + "\", " +
                            "oauth_signature_method=\"HMAC-SHA1\", " +
                            "oauth_timestamp=\"" + oauthTimestamp + "\", " +
                            "oauth_nonce=\"" + oauthNonce + "\", " +
                            "oauth_version=\"1.0\", " +
                            "oauth_token=\"" + oauthToken + "\", " +
                            "oauth_signature=\"" + OAuth.percentEncode(oauthSignature) + "\"";

                    Log.w(TAG, "Authorization : " + authorization);

                    request = request.newBuilder()
                            .addHeader("Authorization", authorization)
                            .build();
                    return chain.proceed(request);
                }
            }).addInterceptor(interceptor).build();

OAuth.java

public static String percentEncode(String s) {
    if (s == null) {
        return "";
    }
    try {
        return URLEncoder.encode(s, ENCODING)
                // OAuth encodes some characters differently:
                .replace("+", "%20").replace("*", "%2A")
                .replace("%7E", "~");
        // This could be done faster with more hand-crafted code.
    } catch (UnsupportedEncodingException wow) {
        throw new RuntimeException(wow.getMessage(), wow);
    }
}

OAuthSignature.java

import android.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class OauthSignature {

public static String generateSignature(String signatueBaseStr, String oAuthConsumerSecret, String oAuthTokenSecret) {
    byte[] byteHMAC = null;
    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec spec;
        if (null == oAuthTokenSecret) {
            String signingKey = OAuth.percentEncode(oAuthConsumerSecret) + '&';
            spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
        } else {
            String signingKey = OAuth.percentEncode(oAuthConsumerSecret) + '&' + OAuth.percentEncode(oAuthTokenSecret);
            spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
        }
        mac.init(spec);
        byteHMAC = mac.doFinal(signatueBaseStr.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new String(Base64.encode(byteHMAC, Base64.DEFAULT));
}
}
Kelvinkelwen answered 20/4, 2016 at 12:7 Comment(9)
What you are passing in Header ?Naked
signpost library is handling header. it includes Authorization OAuth variables.Kelvinkelwen
Check first in Rest ClientNaked
what should I check exactly ? all characters are working but '@' character is not working and it is breaking up my authorizationKelvinkelwen
This is not an issue. Issue is related to the Header that you generated by SignPost. copy/paste that header and try in rest Client (make one reuqest)Naked
well, this is my "Authorization" header : OAuth oauth_consumer_key="consumer_key", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1461155252", oauth_nonce="random_nonce_string", oauth_version="1.0", oauth_token="authenticated_token", oauth_signature="BsvKUWffpSHx5N%2Fkf6F4%2F5CzxCs%3D%0A"Kelvinkelwen
Still my question is how to generate this Header? where is the codeNaked
I just added the manual my oauth signing code. can you check again please ?Kelvinkelwen
Let us continue this discussion in chat.Naked
D
4

I suggest go with fabric - https://fabric.io which has twitters various libs like twitter login, crashlytics and alss you need to setup fabric plugin with android studio. Post that you will be able to post/retrieve you tweets irrespective what you want to post.

For your question - check that '@' is special symbol where by retrofit is causing a problem. These kind of issues come up with retrofit which I have faced in different scenarios.

Try using Fabric for Twitter Login/oAuth

Directional answered 29/4, 2016 at 2:13 Comment(5)
I am using login/oauth for fabric's twitter-kit. I actually just using it for every action but fabric library did not complete library. for example it doesn't include 'retweets_of_me' endpoint. so I decided to move twitter rest api via retrofit. fabric api is using retrofit too. everything is going well with rest api except of using '@' symbol in status parameter :) do you know is there any working around of retrofit for this problem ? or how fabric api handled this situation via retrofit ?Kelvinkelwen
Hey, see if this link is helpful for retweeting linkDirectional
I am not using any kind of tweet-ui package. I have my custom tweet views. I think fabric's twitter library design is not good enough. another example when I compile fabric twitter library, it adds 'digits' library too. this means +14 'unnecessary/unused' activity to adding to your application.Kelvinkelwen
Not sure about it. I am using fabric I haven't face any such kind of issues. Any ways I am doubting your '@' character issues might be Retrofit as it may not be able to parse. I am also using retrofit-2.0-beta-2. Will update you on thisDirectional
okay, if you need I am using retrofit version "2.0.0". I will wait for right solution.Kelvinkelwen
S
0

You must encode of your url, @ => %40 . It work fine, I've been tried (y).

Stringhalt answered 20/10, 2017 at 11:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.