gpt4 book ai didi

api - 使用 Google API、Swift 中的 AFNetworking 缩短 url

转载 作者:可可西里 更新时间:2023-11-01 01:40:46 24 4
gpt4 key购买 nike

在 Google 文档 ( https://developers.google.com/url-shortener/v1/getting_started ) 中,要使用 Google URL shortener,我应该提出如下请求:

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

Content-Type: application/json

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

他们还说我必须进行身份验证:

"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 应用程序创建了一个公钥。然后我使用以下代码进行 POST(AFNetworking,使用 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)。

请告诉我如何修复它。

最佳答案

您缺少的是为此请求设置正确的 AFNetworking 序列化程序。

由于 Google 响应采用 JSON 格式,因此您应该使用 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 - 使用 Google API、Swift 中的 AFNetworking 缩短 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30071395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com