Using accept header with NSMutableURLRequest on iOS - ios

I have a problem with my NSMutableURLRequest. My server supports both JSON and XML formats and they are separated with an access header. It also defaults to JSON if no access header is set.
Which basically means that when I want the response in XML I need to create a request with 'application/xml' as access header.
The problem I'm facing now is that even if I pass in the correct access header to get the response in XML I still end up with JSON (because that's default). It's like my request disregards the access header. Is there anything else I need to create in order to make my request work with headers?
The request is really simple:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
I have confirmed that my request contains my headers by printing allHTTPHeaderFields:
headers: {
Accept = "application/xml";
}

May be use should provide Content-Type?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/xml" forHTTPHeaderField:#"Content-Type"];
Because "application/xml" is always passed in "Content-Type" header field.

Related

How do I get _all_ the NSURLRequest data?

I'm going to be using a different protocol, so probably implementing a NSURLProtocol handler. Anyway, the server still basically wants a HTTP request. Which I have already when I'm talking HTTP.
I suppose I can serialize it but the code must be out there somewhere...just not sure where. Anyone know?
Eg: I want this....from a NSURLRequest
POST /some/control/endpoint HTTP/1.1
Header: Blah blah
Header2: Foo Bar
[Body data here]
Thanks
If you're asking how to construct the request, it is basically:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:...];
[request addValue:#"Blah blah" forHTTPHeaderField: #"Header"];
[request addValue:#"Foo Bar" forHTTPHeaderField: #"Header2"];
request.HTTPMethod = #"POST";
Then create an upload task and provide the body data. Note that you'll also probably have to include Content-Length and Content-Type headers, too.
But if you're asking how to get the data in the format you show above from a request, you pretty much have to construct it yourself with string concatenation. Remember that you need to send \r\n at the end of each header line to be spec-compliant.
Or if you need a fully compliant protocol implementation, it might be simpler to create yourself a local listen socket, point NSURLSession at it, capture the request, forward it, capture the response, and forward it back.

Change NSMutableURLRequest's default header

I need to change a default HTTP header "Connection" in NSMutableURLRequest to "close" value, instead of "keep-alive". What is the best practice to do it?
I tried to use TCP level and create HTTP request myself + use GCDAsyncSocket. It works, but I think this solution looks not very nice.
Thanks.
As simple as u can think of:
NSMutableURLRequest* request = [NSMutableURLRequest alloc] initWithURL:url];
[request setValue:#"close" forHTTPHeaderField:#"Connection"];
If u want to add value:
[request addValue:VALUE forHTTPHeaderField:#"Connection"];

Authentication Issue with REST call for iOS

I am currently trying to make a REST call from an iOS device. My code is below
NSString *restCallString = [NSString stringWithFormat:#"MyURL"];
NSURL *url = [NSURL URLWithString:restCallString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"GET"];
[request addValue:Value1 forHTTPHeaderField:#"Header1"];
[request addValue:Value2 forHTTPHeaderField:#"Header2"];
[request setURL:[NSURL URLWithString:restCallString]];
#try{
_currentConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
#catch(NSError *e){
NSLog(#"%#", e.description);
}
Whenever this is called, I get the following error: Authentication credentials were not provided. However, what confuses me is that if I send an identical GET request via a HTTP web console, it works perfectly. In other words, using the same URL and the same 2 header-value pairs, I get a valid response on a web console, and see no authentication errors. What could be causing this?
You are setting the HTTP headers. This won't work, because the HTTP header is not contained in $_GET or $_POST because they're are not content, but description of the content expected.
Try this instead:
NSURL *url = [NSURL URLWithString:[restCallString stringByAppendingFormat:#"?Header1=%#&Header2=%#", Value1, Value2]];
Of cause you have to be aware that the URL is RFC 1738 compliant.
if I send an identical GET request via a HTTP web console, it works perfectly
I suspect your web console is leveraging SessionAuthentication — i.e. If you're already logged in to your site in your browser the API will authenticate you based on your session cookie.
Django Rest Framework provides various authentication methods and there are third-party options too. The simplest to get going is probably the provided Token Auth method.
Make sure this is enabled. Create a token in the admin (or via the provided view) and make sure you've set the Authorization header. It needs to look like this:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
So your Objective-C will go something like:
[request addValue:[NSString stringWithFormat:#"Token %#", yourToken]
forHTTPHeaderField:#"Authorization"];
Hopefully that gets you started.

Set the header in ASIHTTPRequest

I'm using ASIHTTPRequest to access a web based API and need to set a header for App authentication. Note that this is not a server level authentication it is at API level. I've tried every thing I could find and most of the answers on the web as well as the ones here at www.stackoverflow.com tell me to use something like:
[request addRequestHeader:#"username" value:#"asdf"];
This does not work for me. The guy who built the API I'm using told me that I need to set the header as:
Authorization: TRUEREST username=PersonName&password=pass&apikey=dfiu6aewruif3Bismillah4Rah3anArahimiImi22MyDad
So I tried the following:
NSURL *url = [NSURL URLWithString:#"http://ifish-uk.co.uk/rest_users/login.json"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addRequestHeader:#"username" value:#"MyUser"];
[request addRequestHeader:#"password" value:#"MyPass"];
[request addRequestHeader:#"apikey" value:#"dfiu6aewruif3Bismillah4Rah3anArahimiImi22MyDad"];
But it didn't work... I even tried setting the Request type to GET because the developer told me I should do this:
[request setRequestMethod:#"GET"];
This didn't work... The API developer told me he is made this module as follow:
POST /rest_catches/add.json HTTP/1.1
Host: ifish-uk.co.uk
Authorization: TRUEREST username=MyUser&password=MyPass&apikey=dfiu6aewruif3Bismillah4Rah3anArahimiImi22MyDad
Cache-Control: no-cache
any help would be greatly appreciated.
You should add only one header is Authorization no need to add separate headers for each field (use, pass, etc).
Fill it with your specific values and send.
[request addRequestHeader:#"Authorization" value:#"TRUEREST username=PersonName&password=pass&apikey=dfiu6aewruif3Bismillah4Rah3anArahimiImi22MyDad"];
Did you try adding:
[request setRequestMethod:#"POST"];
?

iOS - REST Client works fine while NSURLRequest returns NULL

I'm trying to download a file from a cloud via a GET HTTP request, and in my REST Client (Postman for Chrome) I get the results as expected, but when I pass the request in iOS, I get a NULL response. What could be the problem?
In my REST Client, I pass the URL as http://myserver.com/api/download.json?filepath=/&fileid=document:1pLNAbof_dbXGn43GtMNafABMAr_peTToh6wEkXlab7U&filename=My Info.doc with a header field for a authorization key, and it works perfectly fine.
While in iOS, if I do such a thing:
[request setURL:[NSURL URLWithString:URLString]]; // I tried even to hardcode the
// URLString to be one of the
// working URLs from the Postman
// Client, doesn't work as well.
[request setHTTPMethod:#"GET"];
NSData* response = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponseList
error:&requestErrorList];
response is null, and I get a status code 500.
Anyone know how to make this work? Thanks.
it looks like your URL has a space in it, you'll need to escape that before sending the string to NSURL.
it would also be helpful to know what the full error from your server is if this doesn't work. what does requestErrorList contain?
but if the only problem is the non-escaped characters something like this should work.
NSString *encodedString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[request setURL:[NSURL URLWithString:encodedString];
An HTTP status code 500 occurs when the webservice is not able to handle your request. An internal error occured.
Try to add some more details to your request.
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];

Resources