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.
Related
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);
Simple as it is:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:linkURLString]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:10];
[request setValue:#"application/json" forHTTPHeaderField:#"ContentÂ-Type"];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:nil]];
If I log the value for the header #"ContentÂ-Type" I got nil. And that what I got at the backend. Every other value is set and even tried other header fields, works fine!. I tried setting the body before the header and still got nil.
I tried to copy and paste your code and I obtained (null) as well.
By printing the list of all HTTPHeaderFields ([request allHTTPHeaderFields]) I got:
Content-Type: {
"Content\U00ad-Type" = "application/json";
}
As you see, there is a strange Unicode character: \U00ad.
This is the reason why when you try to get the value associated with Content-Type, it finds null.
So I tried to reolace the string #"Content-Type" in your code, and the result was:
Content-Type: {
"Content-Type" = "application/json";
}
And indeed now, logging:
NSLog(#"Content-Type: %#", [request valueForHTTPHeaderField:#"Content-Type"]);
I obtained:
Content-Type: application/json
Hi I'm new to iphone development, I'm currently working with a project where I have a screen, in which user should enter their details, like username and password. I googled and find out about NSURLConnection for GET/POST/DELETE. I can GET data by the below codes,
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://************/api/Users"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-
Type"];
NSURLResponse *response;
NSData *GETData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
NSString *ResultData = [[NSString alloc] initWithBytes:[GETData bytes] length:[GETData
length] encoding: NSASCIIStringEncoding];
NSLog(#"ResultData: %#", ResultData);
But for POST method, i doesn't get any ideas of , how it functions and how it store record to sql server database, can't understand whether it s storing data or not, i tried the following codes,
username = #"Aravind.k";
password = #"1234/";
email = #"sivaarwin#gmail.com";
NSString *post = [NSString stringWithFormat:#"FirstName=%#&LastName=%#&WorkEmailAddress=%#",
username, password, email];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://*********/api/Users"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"request: %#", request);
NSLog(#"postData: %#", postData);
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:nil];
NSLog(#"POSTReply: %#", POSTReply);
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes]
length:[POSTReply length]
encoding:NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
Same api url for both GET and POST, any suggestions regarding POST and DELETE will be grateful, Thanks in advance.And how we can get notified as the entered data is stored into the server.
First off: not checking for errors automatically leads to down votes ;)
Please edit your code with full error checks!
When using a MIME type application/x-www-form-urlencoded you need to properly encode the parameters.
I would suggest, to create a NSDictionary holding your parameters, e.g.:
NSDictionary* params = #{#"FirstName": firstName, #"LastName": lastName, #"password": password};
and then use the approach described in the following link to get an encoded parameter string suitable for using as a body data for a application/x-www-form-urlencoded message:
How to send multiple parameterts to PHP server in HTTP post
The link above implements a Category and a method dataFormURLEncoded for a NSDictionary which returns an encoded string in a NSData object:
NSData* postData = [params dataFormURLEncoded];
Note: The MIME type application/x-www-form-urlencoded does not have a charset parameter. It will be ignored by the server. You should set the header like below:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
Otherwise, your code should work. I would strongly recommend to use the asynchronous version of the convenient method:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue *)queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
I have a WCF web-service. If I just put the URL into the browser, I will get the error message: Forbidden. But if I post data through Fetcher(a HTTP Simulator in OS X), I can get the correct return value.
Now, I tried to use NSURLConnection to post data to the web-service and fetch the return value.
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:postURL];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse * response = nil;
NSError * error = [[NSError alloc] init];
receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * receivedStr = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
But all I get is just the html code of the error page I can see from the browser(that forbidden message).
Please help me figure it out. Thanks in advance.
EDIT:
I set up a PHP server and try to do the same thing. I works perfectly. Therefore, I highly doubt it is the WCF problem. Anyone has some good ideas?
if you use generated .svc service you need to :
change
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
to
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-type"];
also you need to SOAPAction field according to operation you request
What is you postData?
I am using a NSMutableURLRequest to send a (synchronous) POST request to a web service.
The request body contains a combination of XML and JSON. Something like :
<element>
<element 2>
<![CDATA[
{"jsondata1":{"datafield1":"data1"},
"jsondata2":"some data"
}
]]>
</element 2>
</element>
the JSON string has been escaped (Using escape() in Javascript)
When I receive the request at the other end I notice that all escaped characters have been unescaped!!
Can anyone tell me why this is happening? And how can I prevent this?
Here is the code that I'm using to send the request:
NSURL *url = [NSURL URLWithString:#"https://my-webservice.com/something.do"];
NSData *xmlResponseDataSave;
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[xmlRequestString length]];
[req addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
NSData *saveData=[xmlRequestString dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPBody:saveData];
NSError *error=nil;
NSURLResponse *resp=[[NSURLResponse alloc] init];
xmlResponseData=[NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&error];
NSString *xmlResponseString=[[NSString alloc] initWithData:xmlResponseData encoding:NSUTF8StringEncoding];
Please note: I cannot make any change to the xml or the web service. I can only change the objective c code.
After a lot of trial and error the only solution that I could come up with is to string used in the request body before sending it (Since it's gonna get unescaped while being sent):
xmlRequestString=[xmlRequestString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *saveData=[xmlRequestString dataUsingEncoding:NSUTF8StringEncoding];
Though this is not a fix in the truest sense, just a work around. But it works for me (So far).
I'm still clue less about the root cause of the problem and I am still looking for a more elegant solution.