RESTKit response.url changed order of parameters - ios

I'm using RESTKit to get data from a rest-api.
This is the URL i set for my request, here's the log just before the request goes off.
2014-04-03 15:51:10.186 xxx[35745:60b] Just sent URL: /api/dspObjGetNewsList?action=coverage&count=30&start=0&open=0&user=xxx&unique=36027&type=all&country=Sweden,global&division=Strategic Industries,Regional Sales and Service,Automotive
Then i log the reponse URL.
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {
NSLog(#"xxx: %d, url: %#", [response statusCode], response.URL);
And i get this?
xxx: response code: 200, url: url/api/dspObjGetNewsList?unique=26791&type=all&division=Strategic%20Industries%2CRegional%20Sales%20and%20Service%2CAutomotive&user=xxx&action=coverage&open=0&country=Sweden%2Cglobal&count=30&start=0
Why am i getting a different URL in my response? Does RESTKit modify my url?

Have you configured HTTPClient properly? Use - (id)initWithHTTPClient:(AFHTTPClient *)client method to configure HTTPClient. For instance:
AFHTTPClient *HTTPClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"www.url.com"]];

Your first log appears to be a raw string of the URL. The second log appears to be the % escaped URL version of that string. This isn't a RestKit thing, it's a URL loading system thing. Certain characters need to be escaped so that they are valid for use in a URL.
For example, your original string has a number of spaces in it. This isn't allowed in a URL and each must be changed to %20.
Why the parameters change order isn't clear - it depends on how you created the string and supplied the parameters to RestKit. But, the order doesn't matter to the processing so you shouldn't need to worry about it.

Related

Post Method with NSDictionary Values using Swift

I'm completely new toSwift. I need to hit a Post Method webservice with NSDictionary parameters & get the JSON response. I tried usingAlamofire & also NSMutableUrlRequest. Nothing seems to workout for me. I either get 'JSON text did not start with array or object and option to allow fragments not set' error or 'Undefined Variable' response from the server. The same service works fine when I try using Objective-C. As I said earlier, I am completely new toSwift & need your assistance.
My base url: http://myofficeit.in/bizfeed/webservices/client.php
Parameter I wanna Pass:
Parameter =
{
UserName = xyz;
deviceModel = iPhone;
deviceToken = "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e";
emailid = "xyz#gmail.com";
location = Asia;
userMobileNo = 1234567890;
};
functionName = register;
The code I used for hitting the service is: http://pastebin.com/aaT4uhS7
Thanks
you can use like
let param: [String:AnyObject] = [
"UserName": iPhone,
"deviceToken": "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e",
"emailid": "xyz#gmail.com",
"location": Asia,
"userMobileNo": 1234567890
]
Alamofire.request(.POST, "http://myofficeit.in/bizfeed/webservices/client.php/register", parameters: param).responseJSON { (req, res, json, error) in
print(req)
print(res)
print(json)
print(error)
}
for sample request in Alamofire
As broad as your question is, the broad will be my answer:
The first thing to do, is to get a clear idea about the web service API, which also requires a basic knowledge of the HTTP protocol. So, what you need to understand is, what the server expects in HTTP terminology.
You eventually will find out, how the server will expect its "parameters". Note, that there is no term like "parameters" in the HTTP protocol. So, you need to map them into something the HTTP protocol provides.
Most likely, in a POST request, "parameters" are transferred as the body of the HTTP message, as a content-type which is application/x-www-form-urlencoded, multipart/form-data or application/json.
According to the needs of the server, and with your basic knowledge of HTTP and NSURLSession, NSURLComponents etc., you compose the URL and the body of the request, set Content-Type header and possibly other headers and you are ready to go.
How this eventually looks like is given in the answer of #AnbyKarthik, which used Alamofire, and a command that composes a POST request whose parameters are send in the body whose content-type is x-www-form-urlencoded.

AFNetworking 2.0 how to put some parameters in the query string of a POST request

I need to call a ws to send an image to a server. Who mades the webserver, decided that the session token should be sent trough the URL and not in the body.
The query should look like: http://api.service.com/imageupload.php?token=434353435 and in the body there should be the image with its parameter.
The session manager when I use the -POST methods puts all the parameter inside the body.
Is there a way to say to the request serializer to put some parameters in the query string and others in the body? or do I need to subclass it?
This can be done like this
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:[#"Google.com" stringByAppendingString:AFQueryStringFromParametersWithEncoding(parameters, NSUTF8StringEncoding)]]] ;
Where parameters is a dictionary

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);
}];

What is Mediafire expecting on upload request

I'm attempting to upload a file using Mediafire's API. Its not clear to me what they expect in the body of the message. I'm attempting to follow the API described in https://www.mediafire.com/developers/upload.php#upload
My understanding is that some parameters are passed in a query string as part of the URL. I'm passing the session_token on the URL.
I set an HTTP header for the file size, x-filesize.
I'm setting the method to POST and sending to base url (before the query string) http://www.mediafire.com/api/upload/upload.php
Its not clear to me what should be in the body. I tried including the pure data from the file being uploaded. I've also tried adding more data to make it look like multipart form.
In either case I'm getting no response at all from the server. I'm doing this in objective-c on a Mac. The NSURLConnection request comes back with nil response and nil error. I'm using
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
The Mediafire upload API is expecting parameters to be send in the URL as the query string, GET style.
The data from the file is included in the body as a multipart form. If the body is improperly constructed, Mediafire may not return a relevant error.
Headers specified in the API are sent as headers in the body.
The 'path' parameter only appears to be honored if a uploadkey is also provided. No error is provided indicating if the path parameter was honored.
Maximum file size appears to be around 4MB.

How to send a XML formatted POST request with RestKit 0.20.1

I have an iOS app that is using RestKit 0.20.1 to pull data from a server. The server at this time can send JSON formatted data but is not able to receive JSON formatted data.
This is where my problem is. POST requests require HTTP Body and the server is set up to receive XML. I have implemented the RKXMLReaderSerialization add on so I can receive XML but I can't find any current way of sending an XML formatted HTTP Body with RestKit.
This question "Send post request in XML format using RestKit " is what I was looking for but the answer from Imran Raheem is now (as far as I can tell) obsolete due to changes in RestKit.
I am using this method for the POST
[[RKObjectManager sharedManager] postObject:nil path:#"/rest/search?ip=255.255.255.0" parameters:search success:nil failure:nil];
Here is what the RestKit objectManager says about the postObject method
/**
Creates an `RKObjectRequestOperation` with a `POST` request for the given object, and enqueues it to the manager's operation queue.
#param object The object with which to construct the object request operation. If `nil`, then the path must be provided.
#param path The path to be appended to the HTTP client's base URL and used as the request URL. If nil, the request URL will be obtained by consulting the router for a route registered for the given object's class and the `RKRequestMethodPOST` method.
#param parameters The parameters to be reverse merged with the parameterization of the given object and set as the request body.
#param success A block object to be executed when the object request operation finishes successfully. This block has no return value and takes two arguments: the created object request operation and the `RKMappingResult` object created by object mapping the response data of request.
#param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
If I have the MIMEType set to JSON the Trace shows my request.body is being populated like so request.body={"Search":"Trending"}.
However if I set the MIMEType to XML the Trace shows the request.body=(null)
Here is the line I use to change the MIMEType
[RKObjectManager sharedManager].requestSerializationMIMEType = RKMIMETypeJSON;
I am pretty new to iOS and Objective-C so I may be setting up the NSDictionary that is used in the parameters of the `postObject' method wrong. Here it is just in case....
NSArray *objects =[NSArray arrayWithObjects:#"trending", nil];
NSArray *keys =[NSArray arrayWithObjects: #"Search",nil];
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
self.search=params;
Any help would be greatly appreciated! Given that I am new Snippets are especially helpful!
Oh and BTW if anyone can point me to REST method that accepts JSON input I would gladly pass it on to my server guy so I can just avoid XML all together.
As feared and suggested in other posts on this topic writing XML is not supported in version of RestKit 0.20.1. Here is a link to my conversation with Blake Watters on the subject.
https://github.com/RestKit/RestKit/issues/1430#issuecomment-19150316
I never did clear up why the request.body= (null) when the MIMEType is set to XML.
The manager of the server has agreed to set it up to receive JSON. That is how I plan to work around this.

Resources