Reputation: 251
I am a beginner at this and I am really stuck. I want to upload a product by sending a POST request to the mentioned URL with an autogenerated client ID and product JSON sent as parameters. Plus I also want cookies in this request. I am finding this incredibly difficult to achieve with Alamofire, hence an NSURLConnection solution is equally welcome. Please help. Thanks in advance!
HTTP POST Request URL: http://blahblah.com/api/v1/products/saveDraft
HTTP Request Headers:
version: 0.1.7
Cookie: client=iOS; version=0.1.7; sellerId=SEL5483318784; key=178a0506-0639-4659-9495-67e5dffa42de
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 1431
HTTP URL parameters: clientId=1444657827384-344b7992-8608-49b1-976a-f405defa189&[PRODUCTJSON]
The Alamofire request I tried to execute is given below. The request fails with Bad Request Error (Status code 400)
let cookies = "client=iOS; version=" + version + "; sellerId=" + sellerId + "; key=" + sellerKey
let manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Cookie": cookies
]
Alamofire.request(.POST, ServerConfig.ADD_PRODUCT_URL, parameters: productJSON, encoding: .JSON, headers: nil)
.responseJSON(completionHandler: { responseRequest, responseResponse, responseResult in
print(responseRequest!.URL)
print(responseResponse)
print(responseResult)
})
Please note that the Product Json does not include the client ID. I still have to figure out a way to include them both as parameters in the HTTP POST request.
Upvotes: 1
Views: 5147
Reputation: 101
@godlike's answer is good, however you need to separate the postString parameters with ampersands not semicolons:
postString = "client=iOS&version=" + version + "&sellerId=" + sellerId + "&key=" + sellerKey
That worked for me.
Also, depending on where your input is coming from, you may want to consider encoding your variables to escape special characters. If they are coming from a user's input you could do something like this:
let encodedUserMessage = userMessage.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
I would have just commented on @godlike's answer but I don't have enough reputation. Hopefully that helps someone else out as I have just spent ages trying to figure out how to pass multiple parameters in.
Upvotes: 2
Reputation: 1928
This is the way I am doing my post requests:
let request = NSMutableURLRequest(URL: NSURL(string: "http://blahblah.com/api/v1/products/saveDraft")!)
request.HTTPMethod = "POST"
var postString: String?
postString = "client=iOS; version=" + version + "; sellerId=" + sellerId + "; key=" + sellerKey
request.HTTPBody = postString!.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
print("ERROR")
}
//DO something
Upvotes: 0