Android HttpGet Url causes "Illegal Character at Index 110" error - indexing

I'm trying to instantiate an HttpGet Object so that I can send a get request to the foursquare api. However, every time I attempt this, (and I've tried it with several different tokens) I get the following error:
java.lang.IllegalArgumentException: Illegal character in query at index 110: https://api.foursquare.com/v2/users/self/checkins?oauth_token=VIHXZZH1ZEXTXOYDFRHHWF42YREWKMNTABDTTVMMF3CSYTKW
It's in the format https://api.foursquare.com/v2/users/self/checkins?oauth_token=OAUTH_TOKEN. You can see my code below. Thanks in advance.
String checkinsUrl = "https://api.foursquare.com/v2/users/self/checkins";
String authUrl = checkinsUrl + "?oauth_token=" + this.token;
HttpGet getMethod = new HttpGet(authUrl);

This was actually just me being stupid. Foursquare sends back a code with is not the access token. You must then make an httpget with that code in order to get the access token.

Related

Format this GET request in VB.NET code behind?

I am trying a "GET" method to request a count of activities from the Accelo API here:
https://api.accelo.com/docs/?http#count-activities
And although i've used a very similar POST method to successfully get the access token using an authentication method, I cannot for the life of me figure out how to get the count of activities. The API says to use "GET" and past the access token as "bearer..." and I've also tried doing a post and getting the stream first, tried sending in some data and accessing the "list activities" endpoint instead...nothing is working. everything I do returns the error "400. Bad Request."
I've tried passing data in a query string format directly in the URI, and tried passing no data since its a GET function. It looks to me like I'm following the API exactly.
Dim data2 = Nothing ' Encoding.UTF8.GetBytes(jsonstring)
Dim _list = GetListOfActivities(New Uri("https://example.api.accelo.com/api/v0/activities/count.xml"), data2, _AccessToken)
Dim reqa As WebRequest = WebRequest.Create(uri)
' reqa.Method = "GET"
reqa.Headers.Add("GET", "/api/v0/activities/count.xml HTTP/1.1")
reqa.Headers.Add("Authorization", "Bearer " & _AccessToken)
reqa.ContentType = "application/x-www-form-urlencoded"
'reqa.ContentLength = jsonDataBytes.Length
' Dim streama = reqa.GetRequestStream()
' streama.Write(jsonDataBytes, 0, jsonDataBytes.Length)
'streama.Close()
Dim responsea As WebResponse = reqa.GetResponse()
Console.WriteLine((CType(responsea, HttpWebResponse)).StatusDescription)
I must be formatting the request wrong - please help?
My problem turned out to be something stupid, and literally beyond the scope of what I posted here. I had specified a "scope" in my initial request to get the access token that was set to read-only "staff" data (I had copied-and-pasted their example online into my code, for other parameters like grant type, and I brought the scope along with it), and in this scenario here I was trying to access "activities" data and not "staff" data. I would have thought I'd get a permissions-related error, instead of "bad request" which confused me, but anyway it works now.
The above code - actually with this line:
reqa.Method = "GET"
instead of this line:
reqa.Headers.Add("GET", "/api/v0/activities/count.xml HTTP/1.1")
Works just fine since I changed my scope to read(all) in my initial web method getting the access token.

Append URL Query Strings to request

I'm trying to send a POST request and format the query string in a specific format. Order doesn't matter aside from the first parameter, but I haven't been successful.
What I need:
localhost/someapp/api/dosomething/5335?save=false&userid=66462
What some of my attempts have spit out:
http://localhost/someapp/api/dosomething/?Id=29455&save=false&userId=797979
http://localhost/someapp/api/dosomething/?save=false&userId=797979
How I formatted the request:
request.AddQueryParameter("Id", "29455");
request.AddQueryParameter("save", "false");
request.AddQueryParameter("user", "4563533245");
If I try AddParameterfor Id it doesn't get appended on the query string (I'm thinking because it's a POST and not a GET), so that won't work. The API isn't expecting a form, it's expecting :
(string id, List<Dictionary<string,string>>)
I could use a StringBuilder, but that feels wrong. I'm not sure if UrlSegment is the best way to go either, since I would basically be hacking the query string. Is there a way to format my request in the format I need using RestSharp's API?
What I ended up using is UrlSegment and then kept the .AddQueryParameter methods, so the final code block looks like :
var url = new RestClient(localhost/someapp/api/dosomething/{id});
var request = new RestRequest(Method.POST);
request.AddParameter("Id", "5335", ParameterType.UrlSegment);
request.AddQueryParameter("save", "true");
request.AddQueryParameter("UserId", "5355234");
Which produced the URI I needed.
The easiest coding process for using RestSharp or any other API client library would be to use Postman to generate if you are unsure of how to code it. Download Postman, do a new request, enter the URL string to send to the API, click on Code, select C# (RestSharp) from the dropdown. Here is the code it generated.
var client = new RestClient("http://localhost/someapp/api/dosomething /5335?save=false&userid=66462");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "bd05aa45-f1b9-4665-a3e7-888ad16f2800");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);

Mediafire api call Signature(session token 2)

i don't see any post related to generating a call signature(session token 2) using mediafire api.So , here is my question.
I am trying to use the get_info api to get the user information but i am having a problem generating a call signature(Session token 2).
I am reading the documentation given here where it says to generate the call signature we need the formula
The signature = the Message-Digest (MD5) of the 'secret_key' modulo 256 + 'time' + the URI of the API call.
I have the secret_key and time which i got from calling get_session_token api.The problem lies (i guess) in the URI of the API call.
In my case , i wanted to call the get_info api , so i replace the URI with "/api/user/get_info.php" .But i got error saying i have invalid signature.What am i doing wrong here?
signature = sha1(email + password + application_id + API_Key)
i see that in here: https://github.com/MediaFire/mediafire-php-open-sdk/blob/master/mflib.php

Authenticate in Xero from Salesforce

I'm new to Oauth and I stack on getting oauth_access_token to work with Xero. Web Service authentication doesn't work for me.
Xero returns the following error message "oauth_problem=signature_invalid&oauth_problem_advice=Failed to validate signature".
The generated signature is incorrect, but what is right way to generate it?
Here is APEX code which generates Endpoint. What is wrong?
Http h = new Http();
String consumer_key='XXX';
Long tmp=(System.now().getTime()/1000);
Blob isItCorrect = Crypto.generateMac('HMacSHA1', Blob.valueOf('https://api.xero.com/api.xro/2.0'), Blob.valueOf(consumer_key));
String signature= EncodingUtil.urlEncode(EncodingUtil.base64Encode(isItCorrect), 'UTF-8');
// Try to get access token
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.xero.com/oauth/RequestToken?oauth_consumer_key='+consumer_key+
'&oauth_signature_method=RSA-SHA1'+
'&oauth_signature='+signature+
'&oauth_timestamp='+tmp+ '&oauth_nonce='+tmp+'&oauth_version=1.0&scope=https%3A%2F%2Fapi.xero.com%2Fapi.xro%2F2.0');
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
System.debug('~~~ '+res.getBody());
It generates following Endpoint:
Endpoint=https://api.xero.com/oauth/RequestToken?oauth_consumer_key=ICSP7Y5K2TG7RIIC6Y7R7KLC1AHWYC&oauth_signature_method=RSA-SHA1&oauth_signature=gWP02y2EIatw4xilTvd5Iq3e0%2Fw%3D&oauth_timestamp=1372123781&oauth_nonce=1372123781&oauth_version=1.0&scope=https%3A%2F%2Fapi.xero.com%2Fapi.xro%2F2.0
Just as an aside: I've never worked with salesforce so I'm not sure if there's a better
way to leverage existing oauth work on the platform, it's very rare
now to have to write all the oauth signature stuff yourself and it's
easy to make a mistake but here goes]
I think your signature base string is incorrect.
As far as I can tell you're just performing HMAC-SHA1 over https://api.xero.com/api.xro/2.0
if you read the OAuth Spec here: http://oauth.net/core/1.0/#anchor14 you need to construct the following base string (based on the request above)
GET&https%3A%2F%2Fapi.xero.com%2Foauth%2Frequesttoken&oauth_consumer_key%3DCONSUMER_KEY%26oauth_nonce (etc etc, just append all your query parameters apart from oauth_consumer as url encoded key=value pairs, in alphabetical order)
and then you need to create the hash with the key CONSUMER_KEY&CONSUMER_SECRET (both CONSUMER_KEY and CONSUMER_SECRET should be parameter encoded as per the OAuth Spec)
That should give you a valid signature..
Edit: I found this library which might be of help: https://code.google.com/p/sfdc-oauth-playground/

FB error:Expected 1 '.' in the input between the postcard and the payload

I have finished my app and then tried it on 3 FB accounts and it was ok,
but the 4th have a permanent error (it cannot get an access token):
com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: Expected 1 '.' In the input between the postcard and the payload.
I tried to remove the app and install it again on this account a few times and nothing changed.
I use Java and restFB client.
This is the code where i get the access token:
if (request.getParameter("code") != null) {
String code = request.getParameter("code");
String url = "https://graph.facebook.com/oauth/access_token?"
+ "client_id=" + clientId + "&" + "client_secret="
+ clientSecret + "&" + "code=" + code + "&" + "redirect_uri="
+ redirectURL +"&type=web_server";
String accessToken=readUrl(url).split("&")[0].replaceFirst("access_token=", "");
//....
}
I saw here someone with the same error, he said that the solution was:
replacing "|" with "%257C" which made my access token invalid"
I couldn't really understand what he means.
Embarrassing as it is -- I'll be honest in case it helps someone else:
When I got this error message, I had accidentally copy/pasted a Google access_token (e.g. ya29.A0A...) into a Facebook graph API route. :)
It's probably worth logging the response to the /oauth/access_token request and the value you extract for use as the access token.
For the account that doesn't work, check whether the /oauth/access_token response includes other parameters before access_token. IIRC I've seen responses like
expiry=86400&access_token=AAAxxxx
Check to ensure you are verifying the "code" parameter returned by Facebook before signing the request, not the "access token". That was the mistake I made.
I experience the same issue, and after debugging my only conclusion was that when this message is thrown it might just be the token is expired or invalid. Checking with a freshly generated token should not throw this error.