Http请求命令行工具

时间:2016-11-10 02:09:38

标签: http https request swift3 httprequest

我正在Swift 3中开发一个命令行工具,我有这个代码:

let url = "www.google.com"
var request = URLRequest(url:url)
request.httpMethod = "GET"

let task = session.dataTask(with: a){ (data,response,error) in

        print("REACHED")
        handler(response,data)


}
task.resume()

如果我在任何网址中使用“http://”或“https://”作为前缀,我无法完成任务,我想知道我是否需要App Transport Security plist,我已经尝试创建一个简单的plist,有谁知道这个问题是否有特殊性?

1 个答案:

答案 0 :(得分:1)

  1. 指定网址时,您需要“方案”(例如http://https://)。

  2. urlURL,而不是String,所以它应该是:

    let url = URL(string: "http://www.google.com")!
    
  3. 是的,如果您想使用Info.plist,则需要http://条目。例如。 https://stackoverflow.com/a/37552442/1271826Transport security has blocked a cleartext HTTP或仅搜索“[ios] http info.plist”或[osx]的堆栈溢出。

    注意,在Xcode 8.1中,控制台应用程序不一定有Info.plist文件,所以如果你没有,你可能需要通过按命令 +来添加一个名词

    add plist

    更新目标设置以指定plist:

    plist target settings

    然后添加适当的设置,例如:

    enter image description here

  4. 我假设您URLRequest(with: a) URLRequest(with: request)的意思是<!DOCTYPE html> <html lang="en"> <head> <title>Age Calculator</title> <script> var birthday; function getAge(birth) { var bday = document.getElementById("bday"); var ageDisplay = document.getElementById("ageDisplay"); var today = new Date(); var curr_date = today.getDate(); var curr_month = today.getMonth() + 1; var curr_year = today.getFullYear(); var pieces = birth.split('/'); var birth_date = pieces[0]; var birth_month = pieces[1]; var birth_year = pieces[2]; if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year - birth_year); if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year - birth_year - 1); if (curr_month > birth_month) return parseInt(curr_year - birth_year); if (curr_month < birth_month) return parseInt(curr_year - birth_year - 1); } var age = getAge(birthday); ageDisplay.value = age </script> </head> <body style="background-color:red"> <form> <fieldset> <label>Type your Date of Birth: </label> <input type="text" id="bday" /> <input type="button" value="click me" onclick="getAge()" /> <br/> <br/> <label>Your Age is: </label> <input type="text" id="ageDisplay" /> </fieldset> </form> <body> </html>

  5. 当您执行请求时,您需要一些东西来保持命令应用程序的活动状态(例如信号量或类似信号)。