Refine URL using Google APIs, AFNetworking in Swift

In the google documentation ( https://developers.google.com/url-shortener/v1/getting_started ), in order to use the Google URL shortener, I have to make a request as shown below:

POST https://www.googleapis.com/urlshortener/v1/url

Content-Type: application / json

{"longUrl": " http://www.google.com/ "}

They also stated that I would have to authenticate:

β€œEvery request that your application sends to the Short API of the Google URL needs to identify your application with Google. There are two ways to identify your application: using the OAuth 2.0 token (which also allows the request) and / or using the application API key."

I chose the public API key as an authentication method: I am creating a public key for my iOS application. Then I use the following code for POST (AFNetworking using Swift):

func getShortURL(longURL: String){ let manager = AFHTTPRequestOperationManager() let params = [ "longUrl": longURL ] manager.POST("https://www.googleapis.com/urlshortener/v1/url?key={my_key_inserted}", parameters: params, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in println("JSON: " + responseObject.description) }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error while requesting shortened: " + error.localizedDescription) }) } 

However, I received the log: Error while requesting abbreviation: Request error: invalid request (400).

Please tell me how to fix it.

+2
url api swift afnetworking
source share
1 answer

What you are missing is to set the correct AFNetworking serializer for this request.

Since Google's answer is in JSON, you should use AFJSONRequestSerializer .

Add manager.requestSerializer = AFJSONRequestSerializer() as follows:

  let manager = AFHTTPRequestOperationManager() manager.requestSerializer = AFJSONRequestSerializer() let params = ["longUrl": "MYURL"] manager.POST("https://www.googleapis.com/urlshortener/v1/url?key=MYKEY", parameters: params, success: {(operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in println("JSON: " + responseObject.description) }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error while requesting shortened: " + error.localizedDescription) }) 
+2
source share

All Articles