Http requests on iOS - ios

So i am trying to make an http request using ASIHTTPRequest class , to send a json file to my server. I was given an android code which is functional and was asked to convert it to iOS code.
I cant understand how to add headers on my request.The android code looks something like this :
private static final String CONTENT_TYPE = "Content-Type";
private static final String JSON_CONTENT_TYPE = "application/json; charset=utf-8";
and then :
request.addHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
On iOS i figured out that the code is something like this :
[request addRequestHeader:#"Content-Type" value:#"Content-Type"];
[request addRequestHeader:#"Json-Content-Type" value:#"application/json; charset=utf-8"];
BUT i got a bit confused , cause on android the request seems to be paired and on iOS the requestHeaders are individually stated. Is this a problem? Should they be paired too on iOS. Am i missing something here? Thank you for reading my post :D

What you want is
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
in the android example, they are just declaring two variables for the header values, they could had simply done something like
request.addHeader("Content-Type", "application/json; charset=utf-8");
which would have had the same effect, so you just need the one line i mentioned above.
also: ASIHTTPREQUEST does not get developed any more (see headline here), so consider using another library for something like this, like AFNetworking

Related

Editing header of all HTTP request made by mapbox-gl-native iOS SDK

I'm using mapbox-gl-native SDK. It can be used with custom servers to provide map tilesets. I'm working with a server which needs an API key in the HTTP request header. I want to edit the header for every request and add the API key.
can anyone help me with this?
I'm using mapbox-gl-native iOS v5.0 (latest untill now)
there is a file named http_file_source.mm in platform/darwin/src/ which is responsible for making HTTP requests. there is a method in this file:
HTTPFileSource::request(const Resource& resource, Callback callback) {
in this mehtod you can see this line:
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url];
this line makes a http request you can add your own header to it, like so: (value for header field)
[req addValue:(NSString *)value forHTTPHeaderField:(NSString *)field]

Setting client name in NSMutableURLRequest

Hi there,
I'm working with a private API and the guy in charge of the API asked me to change the client name I send to the server when making API calls.
I'm using NSMutableURLRequest and for now, I send something like :
< my app name > iOS App version < version of my app >
But that's automatically set and I don't know how to change it.
Does any of you guys have an idea ?
Thanks in advance !
Something like this:
[theRequest addValue:#"MyApplication v1.X.X" forHTTPHeaderField:#"MyAppName"];
You might also consider using the "User-Agent" header:
[theRequest addValue:#"MyApplication v1.X.X" forHTTPHeaderField:#"User-Agent"];

Sailsjs SocketIO in iOS

I'm having a hard time wrapping my mind around a socket based chat app that I'm trying to do. I'm using sailsjs for my server side framework and trying to create a chat based app in iOS using SocketIO-Obj!
I have a successful handshake with the sailsjs framework, and the onConnect method in the sailsjs config/sockets.js file runs. but then after it's open how can I route to the controllers and actions I've created and still be able to access the request socket and subscribe them to my models
Assuming you use the latest version of sails(0.10.0 and later), the protocol that sails uses on socket.io is not public, but you can read the source on the part how it's made, and how it is interpreted.
Basically it will emit an event, with the http verb as the event name and an object method, data, urls and headers. Something like this in Javascript:
var request = {
data: data,
url: url,
headers: headers
};
socket.emit(method, request, callback);
method must be something like 'head', 'get', 'post' and etc.
data should be an object sending the request body. Optional.
url must be a string with no trailing slashes or spaces, like '/buy-a-cat' or '/cat/1/pat'.
headers should be an object, map of header names and values. Header names are lower-cased. Like { accept: '*/*' }. Optional.
I don't know much of objective-C and haven't tested this code, but you can do something like this, I think:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:#"/cats" forKey:#"url"];
SocketIOCallback cb = ^(id argsData) {
NSDictionary *response = argsData;
// do something with response
};
[socketIO sendEvent:#"get" withData:dict andAcknowledge:cb];
Which in http request notation it would be equal to: GET /cats
Note that if you are using sails 0.9.x or lower the protocol is slightly different. Also do note that since sails isn't stable yet(not 1.x.x) this could change again, since this is not documented anywhere.
I have also found a project making sails http calls with SocketIO-Obj. It looks to be using 0.9.x protocol, but should be compatible with 1.x.x.
It looks like you can do this in it:
#import "SocketIO+SailsIO.h"
_socket = [[SocketIO alloc] initWithDelegate:self];
[_socket connectToHost:#"localhost" onPort:1337];
[_socket get:#"/user" withData:nil callback:^(id response) {
NSLog(#"Records: %#", response);
}];

Bug in NSURLRequest or AFNetworking?

Not sure if this is a bug or I am missing something, most likely latter. My AFHTTPClient's base url is:
#define kBaseURL #"http://localhost:4567/api/"
self.client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseURL]];
When I make a request to, for example '/games', it actually sends the request to http://localhost:4567/games ignoring the API part.
The "baseURL" part of "initWithBaseURL:" bit should make it clear that it's only going to work with the scheme + host + port number part.
Once you've created your client, you can add parameters onto it's URL request via techniques like:
NSMutableURLRequest *request =
[self.client requestWithMethod:#"POST" path:#"/api/games" parameters:parameters];
The AFHTTPClient.h file has tons of comments about exactly how to use /s to make sure everything fits together correctly. Check it out on github

wsdl2objc: ContractFilter mismatch at the EndpointDispatcher

We have a .NET WCF Service talking to an iPhone app. I'm using wsdl2objc to generate the objc code required for all the SOAP magic. SoapUI is able to add this service's wsdl and send requests correctly.
But the request generated by wsdl2objc complains about this:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Body>
<s:Fault>
<s:Code>
<s:Value>s:Sender</s:Value>
<s:Subcode>
<s:Value xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">a:ActionNotSupported</s:Value>
</s:Subcode>
</s:Code>
<s:Reason>
<s:Text xml:lang="en-US">The message with Action '' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).
</s:Text>
</s:Reason>
</s:Fault>
</s:Body>
</s:Envelope>
However, If I use the same s:Envelope with SoapUI, the request works correctly. The only difference between the two requests as far as I can see is the header section where wsdl2objc generates this:
SOAPAction:http://xx/AuthenticateDevice
but soapUI generates:
Content-Type: application/soap+xml;charset=UTF-8;action="http://xx/AuthenticateDevice"
I tried to change the code that wsdl2objc generated and replaced this:
[request setValue:soapAction forHTTPHeaderField:#"SOAPAction"];
NSString *contentType = [NSString stringWithFormat:#"application/soap+xml; charset=utf-8;"];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
with this:
[request setValue:soapAction forHTTPHeaderField:#"action"];
NSString *contentType = [NSString stringWithFormat:#"application/soap+xml; charset=utf-8;"];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
But, I just get a 400 error now. Any help is much appreciated!
Thanks,
Teja.
I had a similar issue that was fixed by changing the envelope schema URL in the wsdl2objc output
I changed this
xmlNsPtr soapEnvelopeNs = xmlNewNs(root, (const xmlChar*)"http://www.w3.org/2003/05/soap-envelope", (const xmlChar*)"soap");
to This:
xmlNsPtr soapEnvelopeNs = xmlNewNs(root, (const xmlChar*)"http://schemas.xmlsoap.org/soap/envelope/", (const xmlChar*)"soap");
and it seemed to fix my WCF web-service calls from iOS.
What I think this means is that my version of wsdl2objc is outputting a SOAP 1.1 envelope when the WCF server seems to want SOAP 1.2
Has anyone else noticed this? Is there another way to configure this rather than change after generating the code?
It appears that I was missing begin quote and end quote tags around the action value which was causing this. Here's the code that worked for me, but I'm not happy with setting the action as a part of the http content-type header. So if someone can come up with a better solution, I'd be happy to give credit:
NSString *contentType = [NSString stringWithFormat:#"application/soap+xml; charset=utf-8; action=\"%#\"", soapAction];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
In the WCF services I've worked with I've just passed the value "text/xml" in the Content-Type header and then passed the correct soap action value in a separate SOAPAction header (similiar to the way wsdl2objc was doing it).
Here are a couple things to check:
Is your WCF service using basicHttpBinding - or something else. (I seem to remember reading that bindings other than basicHttpBinding don't work well (or at all) with iOS - but I'm not certain)
What is the correct SOAP action value for this service? In the services I work with it's built using <ServiceNamespace>\<WCFInterfaceName>\<MethodName>

Resources