I want to POST request in the following manner.
POST /oauth/token HTTP/1.1
Host: sandbox.mydigipass.com
Content-Type: application/x-www-form-urlencoded
Accept: */*
code=5bx5vq39nr35ctx954im1g314&
client_id={CLIENT_ID}&
client_secret={CLIENT_SECRET}&
redirect_uri=https://your-site.com/callback&
grant_type=authorization_code
is it possible to make it without ASIHTTPRequest ,is so please reply.
Have you tried with NSURLConnection ? For more, please find the below sample code snippet( Synchronous NSURLConnection request).
NSString *mRequestStr = WEBSERVICEURL;
NSURL *url1 = [NSURL URLWithString:mRequestStr];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url1
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
//[theRequest valueForHTTPHeaderField:body];
[theRequest setValue:mAppDelegate.mResponseMethods_.sessionToken forHTTPHeaderField:#"SessionToken"];
[theRequest setValue:mAppDelegate.mResponseMethods_.authToken forHTTPHeaderField:#"AuthToken"];
[theRequest setHTTPMethod:#"POST"];
NSHTTPURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection
sendSynchronousRequest:theRequest
returningResponse:&response error:&error];
NSString *json_string = [[NSString alloc]
initWithData:responseData encoding:NSUTF8StringEncoding];
int statusCode = [((NSHTTPURLResponse *)response) statusCode];
DLog(#"Fit Bit connect(Re) %# : statusCode: %d", json_string, statusCode);
Related
I've got this problem last time i did some coding in my project, and i just can't seem to find where the error should be located. When i try the URL in the browser on my mac, everything is working fine - and i get the json file displayed.
My code is as following:
NSURL *url = [NSURL URLWithString:#"http://www.overpass-api.de/api/interpreter?data=[out:json];(way(around:150,49.4873181,8.4710548)[\"maxspeed\"];);out body;>;out skel;"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:25];
[request setHTTPMethod: #"POST"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", response1);
NSLog(#"%#", requestError);
NSString *myString = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding];
NSLog(#"myString: %#", myString);
The error that i'm getting is the following:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo=0x1706753c0 {NSLocalizedDescription=unsupported URL,
NSUnderlyingError=0x17044f480 "unsupported URL"}
Bests, Jakob
Adjusted your code and this now seems to work. Basically split end of URL into the body of the POST.
// Split URL from Body
NSURL *url = [NSURL URLWithString:#"http://www.overpass-api.de/api/interpreter"];
NSString *body=#"?data=[out:json];(way(around:150,49.4873181,8.4710548)[\"maxspeed\"];);out body;>;out skel;";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:25];
// Add body to the request
[request setHTTPMethod: #"POST"];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", response1);
NSLog(#"%#", requestError);
NSString *myString = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding];
NSLog(#"myString: %#", myString);
I want to create HTTP request post and get response by using simple Objective C Code method. Here below code to I can post successfully. But I didn't receive response data's. Response printing null value only. Please help me, I need to get response data's.
Here below my code
NSString *post = [NSString stringWithFormat:#"name=%#",name];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:URLPATH]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
// Create GET method
NSError *err;
NSURLResponse *responser;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responser error:&err];
// JSON Formatter
NSError *error;
NSDictionary *jsonsDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *respon = [jsonsDictionary objectForKey:#"response"];
NSLog(#"UPDATE RESPONSE : %#", respon);
You's data post is NSString *post = [NSString stringWithFormat:#"name=%#",name]; . So in this case you need set request header "Content-Type" to "application/x-www-form-urlencoded" or use following code to convert string to data and set Content-Type header:
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
...
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
Its very simple:
//-- Convert string into URL
NSString *jsonUrlString = [NSString stringWithFormat:#"demo.com/your_server_db_name/service/link"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Send request to server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
//-- Send username & password for url authorization
[request setValue: jsonUrlString forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"]; //-- Request method GET/POST
//-- Receive response from server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
Sample : https://github.com/svmrajesh/Json-Sample
I'm trying to post to a webserver in iOS but am receiving a 404 error. The person I'm working with is able to post from a different system with the address and data in a single string:
http://xxx.xxx.xxx.xxx/api/message?salu=mr&firstname=john&lastname=smith&email=smith#testemail.com&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5
I'm trying to do the same with the following code in Xcode:
NSString *body = [NSString stringWithFormat:#"message?salu=mr&firstname=john&lastname=smith&email=matt#testmail.com&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5"];
NSData *data = [body dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [data length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *reply = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", reply);
and the last few lines of 'reply' above from NSLog are:
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/api<br><br>
</body>
However, I'm able to perform a 'GET' on the same address with the following code, where I receive the expected data:
NSMutableURLRequest *request2 = [[NSMutableURLRequest alloc] init];
[request2 setURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api/message"]];
[request2 setHTTPMethod:#"GET"];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
So the web server is functioning and it appears the problem lies in the way I'm posting. Does anyone have an idea of what I'm doing wrong?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api"]];
Don't you notice that you should call NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api/message"]];
/message is part of path, not request body.
and look forward to use some ready framework, such as AFNetworking is.
You've taken the last path component of the request's URL, message, and put that into the body of the request. So, replace:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api"]];
with
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xx.xxx.xxx.xxx/api/message"]];
Also, replace:
NSString *body = [NSString stringWithFormat:#"message?salu=mr&firstname=john&lastname=smith&email=matt#testmail.com&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5"];
with:
NSString *body = [NSString stringWithFormat:#"salu=mr&firstname=john&lastname=smith&email=matt#testmail.com&country=usa&zipcode=99999&checkbox=y&messagelist=message&q1=1&q2=2&q3=3&q4=4&q5=5"];
NSString *clientsec = #"my client sec";
NSString *clientid = #"client id";
NSString *grant = #"urn:ietf:params:oauth:grant-type:migration:oauth1";
NSString *post =[[NSString alloc] initWithFormat:#"client_secret=%#&grant_type=%#&client_id=%#",clientsec,grant,clientid];
NSLog(#"%#",post);
NSURL *url=[NSURL URLWithString:#"https://accounts.google.com/o/oauth2/token"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
i am posting the data like this but i am getting an error like this
"error" : "invalid_request"
can any one solve my problem ... Thanks in advance
This google API must contain 5 arguments.
code - The authorization code returned from the initial request
client_id - The client_id obtained during application registration
client_secret - The client secret obtained during application registration
redirect_uri - The URI registered with the application
grant_type - As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code
Then your actual request might look like this
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
So you have to add code and redirect_uri parameters in your request.
I tried with this one, and worked:
NSString *urlString = #"https://accounts.google.com/o/oauth2/token";
NSURL *url=[NSURL URLWithString:urlString];
NSString *clientsec = #"my client sec";
NSString *clientid = #"client id";
NSString *grant = #"urn:ietf:params:oauth:grant-type:migration:oauth1";
NSString *post =[[NSString alloc] initWithFormat:#"client_secret=%#&grant_type=%#&client_id=%#",clientsec,grant,clientid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%ld", [postData length]];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest* theRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[theRequest setTimeoutInterval:120.0f];
[theRequest setURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPBody:postData];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSLog(#"%#",responseData);
Output:
client_secret=my client
sec&grant_type=urn:ietf:params:oauth:grant-type:migration:oauth1&client_id=client
id 2013-12-10 19:10:07.283 AkbarVenkatConflict[18969:8c03] <7b0a2020
22657272 6f722220 3a202269 6e76616c 69645f63 6c69656e 74222c0a
20202265 72726f72 5f646573 63726970 74696f6e 22203a20 22426164
20726571 75657374 2e220a7d>
From my iPhone app, I'm making a call to an ASP.NET web service. Below is my code
NSString *urlString = #"http://tbtesting/teambinder5/KEY9XXXXXX-cXXe-49XX2-acca-2XXXXXXXa9/Dashboard/DashboardWidgets.asmx/GetAnnouncement";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"en-us" forHTTPHeaderField:#"Accept-Language"];
[request setValue:#"gzip, deflate" forHTTPHeaderField:#"Accept-Encoding"];
[request setValue:#"20" forHTTPHeaderField:#"Content-Length"];
//[request setValue:#"3" forHTTPHeaderField:#"announceIntKey"];
NSError *error = nil;
NSURLResponse *response = [[NSURLResponse alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
NSLog(#"Following error occured: %#", error.localizedDescription);
}
else {
NSString *returnValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"message: %#", returnValue);
}
Here is the header taken from fiddler.
POST http://tbtesting/teambinder5/KEY9XXXXXX-cXXe-49XX2-acca-2XXXXXXXa9/Dashboard/DashboardWidgets.asmx/GetAnnouncement HTTP/1.1
Accept: */*
Accept-Language: en-us
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip, deflate
Content-Length: 20
{"announceIntKey":3}
I'm getting the following error message.
"Message":"Invalid web service call, missing value for parameter: \u0027announceIntKey\u0027."
After a little bit of searching here on SO I found out the cause for this error. It is because I'm not passing the announceIntKey and its value.
Although I know the reason, I'm kinda clueless on how to correct it. Since it looks like an object literal, you can't pass it like any other header value. All the example code I came across here on SO is for jQuery or some other language.
My question is how can I pass this value in Objective C?
Thank you.
It looks like you're sending the content-type of application/json, so it would stand to reason that you need to pass the value as part of a POST containing a JSON body.
You will need to add that to the body of your request. You don't need to set the content-length as the NSMutableURLRequest will manage this for you.
NSString *body = "{\"announceIntKey\" : VALUE}";
[request setHTTPBody:[body dataUsingEncoding:NSASCIIStringEncoding]];
You'll need to replace VALUE with what actually goes into the announceIntKey.