时间戳转换器

Swift 中的 HTTP 获取请求示例

日期:2023-02-24     浏览:323    
【中文标题】Swift 中的 HTTP 获取请求示例【英文标题】:HTTP Get Request Example in Swift 【发布时间】:2016-06-12 17:03:16 【问题描述】:

我正在关注在 Swift 中的 HTTP 获取请求上发布的 Here 教程。

我正在尝试向我自己的 URL 发送 get 请求,将数据作为 JSON 对象接收,将其转换为 NSDictionary 对象,然后解析数据,就像教程一样。

由于某种原因,当我进行“NSJSONSerialization”调用时,我收到了抛出的错误:

“无法读取数据,因为它的格式不正确。”

这是我使用的代码:

import UIKit

import Foundation

func getObject()

    let categoryId: Int = 419247

    let URL = "http://www.URL.com/category/display?category_id=\(categoryId)&_format=json"

    let myURL = NSURL(string: URL)

    let request = NSMutableURLRequest(URL:myURL!)

    request.HTTPMethod = "GET"

    NSURLSession.sharedSession().dataTaskWithRequest(request) 
        data, response, error in

        if error != nil
            print("error=\(error)")
            return
        

        do 
            if let convertedJsonIntoDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary 

                //Parse the data
            
         catch let error as NSError 
            print("Error received")
            print(error.localizedDescription)
        
    .resume()

然后我继续在类中调用此函数“覆盖 func viewDidLoad() 消息,如下所示:

   override func viewDidLoad() 
    super.viewDidLoad()
    score = 0
    scoreLabel.text = String(score)
    getObject()

当我在 catch 块中输入这两行时:

print(error.localizedDescription)
print(String(data: data!, encoding: NSUTF8StringEncoding))

我得到这个结果:

The data couldn’t be read because it isn’t in the correct format.

Optional("<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:fb=\"http://ogp.me/ns/fb#\" xmlns:og=\"http://opengraphprotocol.org/schema/\">\n  <head>\n    <meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\" />\n    <title>**MYTITLE**</title>\n    <meta name=\"description\" content=\**MYCONTENT**/>\n    <meta name=\"keywords\" content=\"**CONTENT**" />\n    <meta name=\"msvalidate.01\" content=\"41B97029358C73B43E83E46F81B33636\" />\n    <link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"http://common.csnimages.com/common/misc/favicon.ico\" />\n    <link rel=\"canonical\" href=\"http://www.URL.com\"/>\n    <style>\n      html, body, div, span, h1, h2\n          margin: 0;\n          padding: 0;\n          border: 0;\n          font-size: 100%;\n          font: inherit;\n          vertical-align: baseline; \n      body\n        font-family:Arial,Helvetica,sans-serif;\n        font-size:13px;\n        color:#4D4D4F;\n        cursor:default;\n        \n      h1\n        font-size:30px;\n        font-weight:bold;\n        color:#783163;\n        \n      h2\n        font-size:16px;\n        font-weight:bold;\n        \n      .wrapper\n        margin:35px auto;\n        width:767px;\n        \n      .redirect\n        background:url(data:image/jpeg;base64,/9j/*ENGLISH TEXT 100,000 CHARACTERS LONG* (REMOVED 95% OF CHARACTERS FOR LENGTH REASONS) AAP/sABFEdWNreQABAAQAAABBAAD/4QNxaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MCA2MS4xMzQ3NzcsIDIwMTAvMDIvMTItMTc6MzI6MDAgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhID);\n\n      var i = new Image(1, 1);\n      i.src = prefix  + q;\n      i.onload = function() ;\n    \n    catch(e);\n\n   </script>\n\n  </body>\n</html>\n")

我似乎根本无法弄清楚这一点。我尝试了很多不同的事情,但都没有成功。任何帮助将不胜感激!

【问题讨论】:

此外,在我执行“if let convertdedJsonIntoDict”调用之前,如果我编写“print(data!)”,它只会打印出一长串十六进制值 @Rob 感谢您的帮助。我打印了数据,它似乎是正确的。在将数据传递给函数之前,我是否需要对其进行编码?当我打印(响应)时,statusCode 是 416 @Rob 你让我做的第一条打印语句中的 JSON 文本?因为那实际上并没有打印我的 JSON 数据,它似乎正在打印这样的内容: Optional("\nw3.org/1999/xhtml\" xmlns:fb=\"ogp.me/ns/fb#\" xmlns:og=\"opengraphprotocol.org/schema\">\n \n \n <i>ENGLISH</i> \n CONTENT" />\n 等等...后面是一长串随机字符和一些英文。 @Rob 刚刚意识到我应该之前发布过这部分。我将 URL 声明为:“http://&_format=json”,所以我相当有信心它应该在 json 中。此外,当我实际访问链接时,我看到了一堆 JSON(当然) @Rob 我确实有问号。我现在将使用该印刷声明中的信息编辑我的问题,我深表歉意。 【参考方案1】:

它的格式不正确,因为它应该是一个数组等。在下面的代码中,如果它给出错误,则更改 JSON 响应类型,如果它不应该显示 JSON 数据。如果 [String:Any] 不起作用,请尝试使用 Array。 一种方法是执行以下代码:

let url = URL(string: "https://google.com")
    let task = URLSession.shared.dataTask(with: ((url ?? URL(string: "https://google.com"))!))  [self] (data, response, error) in
        
        do 
            let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: [])
            print(jsonResponse)
            guard let newValue = jsonResponse as? [String:Any] else 
                print("invalid format")
                
            

        
        catch let error 
            print("Error: \(error)")
        
        
    task.resume()

【讨论】:

相关文章

带有 NSURLSession 的 Swift 中的 HTTP 请求

{】带有NSURLSession的Swift中的HTTP请求【英文标题】:HTTPRequestinSwiftwithNSURLSession【发布时间】:2014-10-1211:10:45【问题描述】:我正在尝试使用NSURLSession在带有Swift的iOS应用程序中发出HTTP请求,但XCode会引发错误。我一直在搜索***和网...}

使用 POST 方法的 Swift 中的 HTTP 请求

{】使用POST方法的Swift中的HTTP请求【英文标题】:HTTPRequestinSwiftwithPOSTmethod【发布时间】:2014-12-0911:44:29【问题描述】:我正在尝试在Swift中运行HTTP请求,将2个参数发布到URL。例子:链接:www.thisismylink.com/postName.php参数:id=13name=J...}

Swift Alamofire HTTP 获取请求

{】SwiftAlamofireHTTP获取请求【英文标题】:SwiftAlamofireHTTPGetRequest【发布时间】:2018-07-1816:32:40【问题描述】:请求代码:staticfunctestRequest()Alamofire.request(Constants.baseURL,method:.get,parameters:["data":"contentpersonson"]).responserespon}

在 Swift 中保存 http 请求的响应

{...615:20:21【问题描述】:我正在尝试在Swift中发出http请求,获取JSON作为响应并将其保存(从中获取所需的数据并以某种方式在屏幕上显示)我正在提出这样的要求funcmakeRequest(base:String,completionHandler:(JSON?,Er}

Swift-4:如何使用带有“Content-Type”的 URLSession 中的参数的 POST 请求获取数据:“application/x-www-form-urlencoded”

{】Swift-4:如何使用带有“Content-Type”的URLSession中的参数的POST请求获取数据:“application/x-www-form-urlencoded”【英文标题】:Swift-4:HowtofetchdatausingPOSTrequestwithParametersinURLSessionwith"Content-Type":"application/x-www-form-}

每两个请求之一中的 Swift Alamofire “请求超时”

{】每两个请求之一中的SwiftAlamofire“请求超时”【英文标题】:SwiftAlamofire"Therequesttimedout"inoneofeverytworequests【发布时间】:2018-08-0212:23:23【问题描述】:在我两次使用相同URL调用loadHeader的每一次中,我都会收到“请求超...}

Android 2.3.3 中的 Http 获取请求

{】Android2.3.3中的Http获取请求【英文标题】:HttpgetrequestinAndroid2.3.3【发布时间】:2012-05-1409:52:26【问题描述】:我在发送HTTPGET请求方面需要帮助。我的代码如下:URLconnectURL=newURL("url");HttpURLConnectionconn=(HttpURLConnection)connectURL.openCon...}

我可以在 Swift 中通过 NSURLSession 以某种方式执行同步 HTTP 请求吗

{...布时间】:2015-01-0305:53:34【问题描述】:我可以通过Swift中的NSURLSession以某种方式执行同步HTTP请求吗?我可以通过以下代码进行异步请求:ifleturl=NSURL(string:"ht}

如何在 PHP 中的 POST 请求后获取 HTTP 响应标头?

{】如何在PHP中的POST请求后获取HTTP响应标头?【英文标题】:HowtogetHTTPresponseheadersafterPOSTrequestinPHP?【发布时间】:2011-09-2520:10:48【问题描述】:我想知道是否可以在不使用cURL的情况下在PHP中的POST请求之后读取/解析HTTP响应标头...}

在 NSURLConnection 中的 Swift 中从 completionHandler 中获取数据

{】在NSURLConnection中的Swift中从completionHandler中获取数据【英文标题】:GettingdataoutofcompletionHandlerinSwiftinNSURLConnection【发布时间】:2014-07-1700:09:19【问题描述】:我正在尝试编写一个执行异步GET请求并返回响应的函数(作为任何数...}

Copyright ©2021 时间戳转换器 小常识 114pp | 陕ICP备18005036号