swift - Pastebin API 不适用于 Swift 4 请求
问题描述
我正在编写一些代码来访问 Pastebin API 并不断遇到这个问题:
Bad API request, use POST request, not GET
我已经尝试了很多东西,但无法正常工作。当我使用cURL
一切正常时,但在我的 Swift 应用程序中调用失败。
func postPasteRequest(urlEscapedContent: String, callback: @escaping (String) -> ()) {
var request = URLRequest(url: URL(string: "http://pastebin.com/api/api_post.php")!)
request.httpMethod = "POST"
let postString = "api_paste_code=\(urlEscapedContent)&api_dev_key=\(API_KEY)&api_option=paste&api_paste_private=1&api_paste_expire_date=N"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil
// check for fundamental networking error
else {
NSLog("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
NSLog("statusCode should be 200, but is \(httpStatus.statusCode)")
NSLog("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
...
}
task.resume()
}
解决方案
task.resume()
在 dataTask 方法的右花括号之后添加。顺便说一句,pastebin 在 Swift 中有一个非常详细的方法,关于如何获取数据。
在这里,您可以快速找到对该 API 的调用。
// Vladimir Zhelnov - neatek.pw - Web/iOS dev
class Class_JSONRequest {
func get_url_post(get_url: String, params: String, completion: @escaping (_ result: NSDictionary) -> Void) {
let myUrl = URL(string: get_url);
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = params;
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
do {
if(data != nil) {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
//print(parseJSON)
completion(parseJSON)
}
}
} catch {
print(error)
}
}
task.resume()
}
}
/* usage:
let post_params = "some=post¶ms=1";
JSON.get_url_post(get_url: "http://..api", params: post_params , completion: { answer in
... something
});
*/
推荐阅读
- html - 如何定位具有焦点状态的锚标签?
- android - Android Studio 代码完成不再起作用
- python - 不同字典的Python排序列表
- php - 带有 Sanctum 401 未授权错误的 Laravel Vue SPA
- node.js - 如何在 Google App Engine 上从代码中找出正在运行的其他实例数量?
- javascript - 在提交表单之前显示 div 不起作用
- excel - 如何使用visual studio和oracle读取带有特殊字符的excel列名
- switch-statement - Zig 0.8.0 错误:“(枚举文字)”类型的值必须是已知的 comptime
- python - 扩展布局添加的输入框的 PySimpleGui Rick Click Menu 剪贴板
- javascript - 使用tailwind css和alpine js 3.x动态调整textarea的大小