Get url shortened with Google API, AFNetworking in

2019-01-20 15:56发布

问题:

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

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

Content-Type: application/json

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

They also stated that I will have to authenticate:

"Every request your application sends to the Google URL Shortener API needs to identify your application to Google. There are two ways to identify your application: using an OAuth 2.0 token (which also authorizes the request) and/or using the application's API key."

I chose public API key as a method to authenticate: I create a public key for my iOS app. Then I use the following code to 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 got the log: Error while requesting shortened: Request failed: bad request (400).

Please tell me how to fix it.

回答1:

What you are missing is setting the right AFNetworking serializer for this request.

Since the Google response is in JSON, you should use AFJSONRequestSerializer.

Add manager.requestSerializer = AFJSONRequestSerializer() like this:

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