此网址与谷歌API缩短,斯威夫特AFNetworking [英] Get url shortened with Google API, AFNetworking in Swift

查看:240
本文介绍了此网址与谷歌API缩短,斯威夫特AFNetworking的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在谷歌文档( https://developers.google.com/url-shortener/ V1 / getting_started ),使用谷歌URL缩短,我应该如下要求:

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

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

内容类型:应用程序/ JSON

Content-Type: application/json

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

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

他们还说,我将不得不验证:

They also stated that I will have to authenticate:

每一个请求您的应用程序发送给谷歌URL缩短API
  需要确定您的应用程序谷歌。有两种方法来
  找出你的应用程序:使用OAuth 2.0令牌(这也
  授权请求)和/或使用应用程序的API密钥。

"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."

我选择了公共API密钥验证的方法:我创造了我的iOS应用程序的公钥。然后我用下面的code到POST(AFNetworking,使用SWIFT):

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

不过,我得到的日志:错误同时要求缩短:请求失败:错误的请求(400)

However, I got the log: Error while requesting shortened: Request failed: bad request (400).

请告诉我如何解决它。

推荐答案

你所缺的是设置AFNetworking串行此请求的权利。

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

由于谷歌的反应是JSON,你应该使用 AFJSONRequestSerializer

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

添加 manager.requestSerializer = AFJSONRequestSerializer()是这样的:

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

这篇关于此网址与谷歌API缩短,斯威夫特AFNetworking的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆