IOS HTTP Request Example - ios6

I am trying make a call to the fitbit API.
I am unsure how to input the HTTP request shown below into my Objective C code in order to make this call and handle the response.
POST /oauth/request_token HTTP/1.1
Host: api.fitbit.com
Authorization: OAuth oauth_consumer_key="fitbit-example-client-application",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1270248082",
oauth_nonce="161822064",
oauth_callback="http%3A%2F%2Fexample.fitbit.com%2Fapp%2FcompleteAuthorization",
oauth_signature="Omf%2Bls2gn%2BDlghq245LRIyfMdd8%3D"
oauth_version="1.0"
A simple example would be helpful. Thank you.

I suggest using an OAuth library to handle the OAuth signature generation. It can be a pain in the ass to wrangle the Authorization header. I've used oauthconsumer with success.
Code sample:
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:oauthConsumerKey secret:oauthConsumerSecret];
OAToken *token = [[OAToken alloc] initWithKey:oauthAccessToken secret:oauthAccessTokenSecret];
OAHMAC_SHA1SignatureProvider *provider = [[OAHMAC_SHA1SignatureProvider alloc] init];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] consumer:consumer token:token realm:nil signatureProvider:provider];
[request prepare];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
In this example, the 5 strings you will provide are:
oauthConsumerKey
oauthConsumerSecret
oauthAccessToken
oauthAccessTokenSecret
urlString

I am trying to do the same thing and oauthconsumer looks quite nice.
Is it because I am not getting the oauthAccessTokenSecret?
[edit] Yes, it was.
I keep getting:
"This page is no longer valid. It looks like you provided an invalid token or someone already used the token you provided. Please return to the site or application which sent you to this page and try again."
[edit] This is because it didn't have the correct token on the url string.

Hi you can get the working FitBit Oauth1.0 Authentication sample code from below link
https://github.com/KaranRajpoot/FitBit

Use OAuth.io, and the OAuth.io iOS SDK, to connect to FitBit.

Related

Ruby 2 intercepting request with Typhoeus

I want to change query params before request is hit using typhoeus. What should be right approach? Do we have interceptors in Ruby as that of Java, should I be using something like before_filter as that in Rails or meta-programming in Ruby?
I just checked there is Typhoeus::Request::Before module to hook request. Can anyone help me out how can I implement it?
I have implemented typhoeus before to change query params just before request gets executed as below. Hope it helps someone.
require 'uri'
Typhoeus.before { |request|
uri = URI.parse(request.base_url)
uri.query = [uri.query, "param1=value1"].compact.join('&')
request.base_url = uri.to_s
request
}

is that possible to send header information in $window.open(url) method

I am downloading the file from the server using API, for that i have to send session details in header, how can i do it using angularjs?. Please help me out.
Thank you in advance for suggestions.
No - It is not possible to send headers in straight way using $window.open
Yes - Its is possible but not straight way, If you've got server-side control then you can set header value in query string and get it parsed from query string on the back-end.
I don't suggest to pass params with window.open.
BUT you can use window.open like this.
var params = {
access_token: 'An access_token',
other_header: 'other_header'
};
//Add authentication headers in URL
var url = [url_generating_pdf, $.param(params)].join('?');
//Open window
window.open(url);
Please check the details info here

Restangular POST data not being read by Django

I've done a lot of searching and nothing seems to fully address this. I've created a REST API that has a resource to send a message. The path is /api/v1/conversation/{type}/{id}/message. Placing a POST call to that URI will create a message for the given conversation.
Everything works great if I just use $.post('/api/v1/conversation/sample/sample/message', {message: "All your base are belong to us"});
However, I'd like to use Restangular, and for some reason, it is sending the POST data in a way that I have to work with request.body instead of request.POST.get('message'). This is terribly inconvenient if I have to do this with every single server side API.
Here's my Restangular code:
conversation = Restangular.one('conversation', scope.type).one(scope.type_id);
conversation.post('message', {message: "All your base..."})
To clarify, it is POSTing to the correct URI, it just is sending the post data as a payload instead of as form data. How can I configure it to send the post as form data?
Edit:
As a side note, I was able to mitigate this issue by creating a utility function:
def api_fetch_post(request):
post = request.POST
if not post:
try:
post = json.loads(request.body.decode(encoding='UTF-8'))
except:
pass
return post
This way I can accept either type of POST data. Regardless, is there a way to send form data with Restangular?
Yes, there is.
var formData = new FormData();
formData.append('message', $scope.message);
// Or use the form element and have formData = new FormData(formElement).
Restangular.one('conversation', $scope.type).one($scope.type_id)
.withHttpConfig({transformRequest: angular.identity})
.post(formData, null, {'Content-Type': undefined})
.then(function(response){
// Do something with response.
});

FBPlacePickerViewController doesn't load any data

I am trying to use FBPlacePickerViewController and it doesn't seem to load any data.
Here is my code:
FBPlacePickerViewController *picker = (FBPlacePickerViewController*)segue.destinationViewController;
picker.navigationController.navigationBarHidden = YES;
picker.delegate = self;
picker.radiusInMeters = 1000;
picker.resultsLimit = 30;
if([TonerAppDelegate instance].lastLocation != nil){
picker.locationCoordinate = [TonerAppDelegate instance].lastLocation.coordinate;
[picker loadData];
}
[TonerAppDelegate instance].lastLocationUpdateFunction = ^{
picker.locationCoordinate = [TonerAppDelegate instance].lastLocation.coordinate;
[picker loadData];
};
It is an embed segue (iOS 6). I verify that the picker is a valid object. The [picker loadData] method does get called, and the coordinate data is perfectly valid. I am not getting any exceptions or warnings. I've allowed my app to access to my location in iOS and I double-verified that in Settings. My iPod is connected to the Internet and the connection works perfectly. All the other apps can use location services without any problem. So, there probably is a problem with my implementation of the place picker. I've also implemented the -(void)placePickerViewControllerDataDidChange:(FBPlacePickerViewController *)placePicker and -(BOOL)placePickerViewController:(FBPlacePickerViewController *)placePicker shouldIncludePlace:(id<FBGraphPlace>) methods of the delegate, and they aren't getting called either. What am I doing wrong?
Thanks,
Can.
Found the answer: I wasn't creating the Facebook session before displaying the place picker. I totally forgot about the session. It'd be nice to see Facebook add an assertion check in loadData method of the picker for an existing Facebook session. I've created the session, and THEN tried my code, and it works perfectly now.

UTF-8 Strings getting scrambled by Restlet on GAE

I have a simple Restlet service hosted on AppEngine. This performs basic CRUD operations with strings and is working well with all sorts of UTF-8 characters when I test it with curl (for all the verbs).
This is consumed by a simple restlet client hosted in a servlet on another AppEngine app:
// set response type
resp.setContentType("application/json");
// Create the client resource
ClientResource resource = new ClientResource(Messages.SERVICE_URL + "myentity/id");
// Customize the referrer property
resource.setReferrerRef("myapp");
// Write the response
resource.get().write(resp.getWriter());
The above is pretty much all I have in the servlet. Very plain.
The servlet is invoked via jquery ajax, and the json that I get back is well formed and everything, but the problem is that UTF-8 encoded strings are coming back scrambled, for example:
Université de Montréal becomes Universit?? de Montr??al.
I tried adding this line in the servlet (before everything else):
resp.setCharacterEncoding("UTF-8");
But the only diference is that instead of getting ?? I get Universitᅢᄅ de Montrᅢᄅal (I don't even know what kind of characters those are, asian I suppose).
I am 100% sure the restlet service is OK, because other than debugging it line by line I am able to test it from cmd line with curl and it's returning well formed strings.
By looking at the http header of the response from firefox (when calling the servlet via javascript) I can see the encoding is indeed UTF-8, as expected. After hours of struggling reading every possible related article I came across this restlet discussion and noticed that indeed I do have Transfer-Encoding: chunked on the http header of the response. I tried the proposed solutions (override ClientResource.toRepresentation, didn't do any good so I tried restlet 2.1 as susggested with ClientResource.setRe​questEntityBuffering​(true), no luck there either) but I am not convinced my issue is related to Transfer-Encoding: chunked at all.
At this point I am out of ideas, and I would really appreciate any suggestions! O_o
UPDATE:
I tried doing a manual GET with a classic UrlConnection and the string is coming back alright:
URL url = new URL(Messages.SERVICE_URL + "myentity/id");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
resp.getWriter().print(writer.toString());
So much for being all RESTful and fancy ...but still I have no clue why the original version doesn't work! :/
I tried doing a manual GET with a classic UrlConnection and the string is coming back alright:
URL url = new URL(Messages.SERVICE_URL + "myentity/id");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
resp.getWriter().print(writer.toString());
So much for being all RESTful and fancy ...but still I have no clue why the original version doesn't work! :/
Does your response contain the appropriate "Content-Type" header? It should be something like "Content-Type: application/json; charset=UTF-8" (note the charset).
Try starting your development server and retrieving your resource from the command line using cURL and inspecting the headers, e.g. curl -i http://localhost:8080/myentity/id. In theory browsers should assume UTF-8 for JSON, but I wouldn't trust on that.

Resources