Alamofire GET request isn't working correctly - ios

I am sending out a GET request like so.
let parameters: Parameters = [
"filter": ["fruit": "apple"]
]
Alamofire.request(urlStr, method: .get, parameters: parameters, encoding:URLEncoding.default).responseJSON { response in
print(response.request!)
}
However, the GET request doesn't work correctly. I believe the parameters are not correct at all. This is the URL request that is printed out using the following code print(response.request!)
https://api.example.com/fruits?apiKey=1&filter%5Bfruit%5D=apple
However, using postman I can send the correct request and get the correct response using the following URL request.
https://api.example.com/fruits?apiKey=1&filter={"fruit":"apple"}
I don't know how to fix this. I tried many encoding types, but none of it worked. Any tips or suggestions are appreciated
Edit: I do get a response from the server using alamofire, but it isn't correct data because the paramters are ignored. However, the response I get from postman is correct.

Morning Curt,
Since there is no published specification for how to encode collection types, the convention of appending [] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for nested dictionary values (foo[bar]=baz) [is used].
In my opinion you should really avoid passing array objects in query strings. You could change your request to something like:
apiKey=1&fruit=apple
Where does presence of field fruit itself indicates response should be filtered.
Moreover:
Instead of using GET, you should consider using POST or PUT and passing values via JSON, XML, or another well-defined format. This could require server side changes obviously.
If server side is out of your control, you should consider manually encoding these parameters instead.
Source
You can find here an example of manually encoding.
Happy coding!

Related

Make HTTP Get request in iOS with params

I want to make an HTTP GET request from my iOS client and place in the request params. I have written code that performs a POST request, where it was very easy to use setHTTPBody to place a NSData* object in the request. How is this done for a GET request?
Thanks
In a GET method the parameters are passed in the query string - so you suffix your URL with something like ?param1=value1&param2=value2&param3=value3. You may need to percent-encode your query string if it contains characters like space, & or =

Form posting JSON data which includes a url is being split at the query string of the url

I need to post JSON data to an MVC controller that contains URL's. The JSON data looks like it's being split at the query string (=)
The JSON data looks like this:
"{"Files":[{"Title":"test","OriginalFileName":"",
"FileName":"http://company.domain.com/auth.aspx?enrollmentkey=APK54cd1546a8454d4ca79ded89a78f8698",
"Categories":[{"CategoryId":76,"SubCategoryId":182,"CatId":"CatId0"}],
"TypeId":"84",
"Tags":["Select Tag(s)..."],
"TagIds":[],
"Roles":[],
"MemberOnly":false,
"ContentTypeId":7,
"Id":0,
"IsPublished":true,
"PublishDate":""}]}"
Debugging, I see that it's being split into
KEY (Request.Form.GetKey(0)):
{"Files":[{"Title":"Test","OriginalFileName":"","FileName":"http://company.domain.com/auth.aspx?enrollmentkey
VALUE (Request.Form.GetValue(0)):
APK54cd1546a8454d4ca79ded89a78f8698","Categories":[{"CategoryId":110,"SubCategoryId":111,"CatId":"CatId0"}],"TypeId":"69","Tags":["Select Tag(s)..."],"TagIds":[],"Roles":[],"MemberOnly":false,"ContentTypeId":7,"Id":0,"IsPublished":true,"PublishDate":""}]}
Does the JSON data needs to be escaped at the = or the whole thing needs to be encoded or am I missing something?
I should note that I'm using knockout's ko.toJSON(js) to create the JSON although I'm not sure that is relevant.
I also noticed that chrome dev tools also seems to recognize the Key-Val split:
If you are sending JSON data to the server, the Content-Type header needs to be set to application/json. If it is set to application/x-www-form-urlencoded then the server will try to interpret the JSON as key-value pairs as in a URL. This is why your JSON string is getting broken in two at the =.

How to POST JSON in body for functional tests in Symfony 1.4

I'm writing some functional tests for a POST API endpoint. I've reviewed the documentation and can't find a way to add content to the POST body. The post method for sfBrowser:
post('some url',array('x'=>'y'))
Only creates POST parameters (in this case x=y). Is there anyway of adding content to the post body using sfBrowser?
From what I have found here, here and here, the POST format takes parameter:value format, so you can send your JSON with some code like:
post('some url', array('json_data' => json_encode($toJson))
and then decode in your action with
$jsonObj = json_decode($request->getParameter('json_data'));
but you need to associate your JSON data with a parameter name in your POST to retrieve it on the server side.
As a side note, after looking at the Symfony code, the parameters are given straight to $_POST except for CSRF, which is tweaked.

Passing array of parameters through get in rails

How do I pass array of parameters through Get method in rails? Currently my URL loocs like this:
http://localhost:3000/jobs/1017/editing_job_suites/1017/editing_member_jobs/new?ids[]=1025&ids[]=1027
How can I pass the array with Get method but avoid ?ids[]=1025&ids[]=1027 part.
Request is being sent with javascript window.open method. Is there any workaround to send not ajax Post request.
You should stick to using a GET request if you are not changing the state of anything, and all you want to to access a read only value.
To send an array of ids to rails in a GET request simply name your variable with square brackets at the end.
//angular snippet
$http.(method:'GET',
...
params: {'channel_id':2, 'product_ids[]': productIds}
//where productIds is an array of integers
...
)
Do not concatenate your ids as a comma separated list, just pass them individually redundantly. So in the url it would look something like this:
?channel_id=2&product_ids[]=6900&product_ids[]=6901
url encoded it will actually be more like this:
?channel_id=2&product_ids%5B%5D=6900&product_ids%5B%5D=6901
Rails will separate this back out for you.
Parameters: {"channel_id"=>"2", "product_ids"=>["6900", "6901"]}
No, GET can only put variables on the url itself. If you want the URL to be shorter, you have to POST. That's a limitation feature of HTTP, not Rails.
I recently wanted to do this and found a workaround that is a little less complex, and so has some complexity limitations but may also be easier to implement. Can't speak to security, etc.
If you pass your array values as a string with a delimiter, e.g.
http://example.com/controller?job_ids=2342,2354,25245
Then you can take the result and parse it back to what you want:
job_ids = params[:job_ids].split(',')
Then do whatever:
job_ids.each do |job_id|
job = Job.find(job_id.to_i)
end
etc
#Homan answer is valid for using an external client (e.g curl or angular). Inside Rails test cases though, you should not use []. Here's an example:
get get_test_cases_url(**path_params), params: {case_ids: ["NON-9450", "NON-12345", "NON-9361"]}
This is using new format where get_test_cases is name of route and you pass to the method all params needed to construct the URL path. Query params are a separate hash.
FYI if I use [] like case_ids[], then instead of ["NON-9450", "NON-12345", "NON-9361"] I'm getting it parsed to [["NON-9450"], ["NON-12345"], ["NON-9361"]]

Assembling SOAP Header manually with Savon

I've been dealing with a "soap message header incorrect" error message when submiting a SOAP request using Savon.
I copy/pasted the exact same xml generated by Savon into SOAPUI and I don't get that error and I get the expected response.
So, since I'm tired of trying different things, I want to assemble my own header without Savon help on that.
What I want to do is something like:
soap.header = "<wbs:Session><wbs:SessionId></wbs:SessionId><wbs:SequenceNumber></wbs:SequenceNumber></wbs:Session>"
However I get this error from Savon:
can't convert Symbol into String
Why?
Thank you in advance.
Its likely caused by the fact you havent set any values.
I was getting this error when I had a hash containing just one custom object on return, as it was trying to access parts of the hash that had automatically been removed. (it removed unnesscary layer of hash for me :#)
I believe the header will only accept a Hash - from the savon.rb page:
Besides the body element, SOAP requests can also contain a header with
additional information. Savon sees this header as just another Hash following
the same conventions as the SOAP body Hash.
soap.header = { "SecretKey" => "secret" }

Resources