首页 > 解决方案 > 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()
}

标签: swiftpastebin

解决方案


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&params=1";
JSON.get_url_post(get_url: "http://..api", params: post_params , completion: { answer in
    ... something
});
*/

推荐阅读