I'm having a weird issue calling an API from my ios app. I create a post request
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5.0];
[request setHTTPMethod:#"POST"];
I then create json to send to the request and add it to the body of the request like so:
[request setHTTPBody:encodedData];
Finally, I am adding a few cookies which I then set with:
NSArray* cookieArray = [NSArray arrayWithObjects: sessionCookie, uidCookie, vidCookie, nil];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
[request setAllHTTPHeaderFields:headers];
This all works fine. However, since I am sending json I'm trying to be good and also set the content type with this line of code:
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField: #"Content-Type"];
As soon as I add this line of code, the data I sent to the body of the request no longer gets passed as part of the request. Does this sound like behavior anyone else has experienced?
I am also using
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
Check this explanation
What does "Content-type: application/json; charset=utf-8" really mean?
Related
I have a string with webservice.But when i add the string into NSMutableRequest, The method return become null.Here is my code,
-(NSMutableURLRequest *)createRequest:(NSString *)convertedString{
NSString *temp=[NSString stringWithFormat:#"%#%#",Api_Link,convertedString];
NSLog(#"%#",temp);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:temp]];
[request setHTTPBody:[convertedString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"App IPHONE" forHTTPHeaderField:#"USER_AGENT"];
[request setHTTPMethod:#"POST"];
return(request);
}
I ran your code in an Xcode Project:
NSString *temp = #"https://www.google.se/";
NSString *temsssp = #"https://www.google.se/";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:temp]];
[request setHTTPBody:[temsssp dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"App IPHONE" forHTTPHeaderField:#"USER_AGENT"];
[request setHTTPMethod:#"POST"];
NSLog(#"%#", request);
Result:
2017-02-15 06:43:23.061816 Sneak[5023:3002603] <NSMutableURLRequest: 0x170218120> { URL: https://www.google.se/ }
So there is nothing wrong with your request if you have a valid URL.
If you need further details and help, provide further information and code on how you run this method, and I will update the answer accordingly as your question changes or is edited.
EDIT:
As I mentioned, you need a Valid URL, I did the NSLog for you with this line:
NSString *temp = #"somethingsomething";
And the results are nil. So again, you need a valid URL.
I came into an issue trying to send files with NSURLSessionUploadTask to a custom REST service.
The problem is that the file seems to get transferred up to an arbitrary size, and then the task stops without any error (URLSession:task:didCompleteWithError: gets called with error set to nil).
The file that needs to be transferred is almost 10MB in size, and I found that smaller files sometimes get transferred correctly.
The code I'm using for creating the task is the following:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"100-continue" forHTTPHeaderField:#"Expect"];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", length] forHTTPHeaderField:#"Content-Length"];
NSURL *fileUrl = [NSURL fileURLWithPath:instanceFilePath];
NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileUrl];
I need to specify some headers for the server to correctly interpret the request, and the length variable is the effective size of the file being sent.
Any idea about what's going on here?
Thanks.
In my application I need to make a PUT type request. I have followed the below steps
NSString *path = #"http://hostname/api/Account/VerifyUser?applicationToken=72B648C6-B2B7-45ED-BA23-2E8AAA187D2C&emailID=xxx#gmail.com&password=aaaaa";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:path]];
[request setHTTPMethod:#"PUT"];
[request setValue:[NSString stringWithFormat:#"%d", string.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[string dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
For POST and GET I am getting correct output.
I have searched a lot but i am not getting any solution.Please suggest me any possible solution .
Thanks in advance
Try this
For xml request body
Set [request setValue:#"application/x-www-form-urlencoded;charset=utf-8;application/form-data" forHTTPHeaderField:#"Content-Type"];
OR
For json request body
Set [request setValue:#"application/x-www-form-urlencoded;charset=utf-8;application/json" forHTTPHeaderField:#"Content-Type"];
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 calling a web service in iOS. For this, I need to set the header in NSMutableURLRequest object. My service takes two string parameters and returns data in JSON format.
What are the the fields that I need to set in the header (Both while using GET and POST) using the setValue:forHTTPHeaderField:.
We do not need to use setHTTPBody: while using GET.. right???
I had the same question and I resolved (using some code from Iducool and Ankit Mehta) like this...
NSURL *theURL = [NSURL URLWithString:#"yourURL"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
//Specify method of request(Get or Post)
[theRequest setHTTPMethod:#"GET"];
//Pass some default parameter(like content-type etc.)
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//Now pass your own parameter
[theRequest setValue:yourValue forHTTPHeaderField:theNameOfThePropertyValue];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
//Now you can create a NSDictionary with NSJSONSerialization
NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:theResponseData options:0 error:&theError];
NSLog(#"url to send request= %#",theURL);
NSLog(#"%#",dataDictionaryResponse);
Look at this code which i am using to call a web service and thats working for me
+(NSString *)http_post_method_changed:(NSString *)url content:(NSString *)jsonContent{
NSURL *theURL = [NSURL URLWithString:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
NSData *requestData = [jsonContent dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody: requestData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *data=[[NSString alloc]initWithData:theResponseData encoding:NSUTF8StringEncoding];
NSLog(#"url to send request= %#",url);
NSLog(#"response1111:-%#",data);
return data;
}
Both while using GET and POST We do not need to use setHTTPBody?
setHTTPBody only make sense when you are using POST request. GET don't need it.
For Header parameters do something like below
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
//Specify method of request(Get or Post)
[theRequest setHTTPMethod:#"GET"];
//Pass some default parameter(like content-type etc.)
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//Now pass your own parameter
[theRequest setValue:yourObj forHTTPHeaderField:#"your parameter name"];
setHTTPBody is used when HTTP method POST is being used.
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:theUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Here the data is nothing but NSData of JSON data that need's to be sent.