最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[已解决]swift 给NSURLConnection NSURLRequest添加header

Swift crifan 1233浏览 0评论

已有代码:

    var decodedJsonDict:JSON?

    let fullNsurl: NSURL = NSURL(string: url)!
    print("fullNsurl=\(fullNsurl)")
    let urlReq: NSURLRequest = NSURLRequest(URL: fullNsurl)
    print("urlReq=\(urlReq)")
    do {
        let response: AutoreleasingUnsafeMutablePointer<NSURLResponse? >= nil
        let respJsonData: NSData =  try NSURLConnection.sendSynchronousRequest(urlReq, returningResponse: response)
        //print("response=\(response)") //response=0x0000000000000000
        //print("respJsonData=\(respJsonData)")

        decodedJsonDict = JSON(data: respJsonData)
        print("decodedJsonDict=\(decodedJsonDict)")
    }catch let httpGetErr {
        print("httpGetErr=\(httpGetErr)")

        decodedJsonDict = nil
    }
现在需要,添加header
Accept:application/json
Content-Type:application/json
搜:
swift NSURLConnection add header
参考:
    var decodedJsonDict:JSON?

    let fullNsurl: NSURL = NSURL(string: url)!
    print("fullNsurl=\(fullNsurl)")
//    let urlReq: NSURLRequest = NSURLRequest(URL: fullNsurl)
    let mutableUrlReq:NSMutableURLRequest = NSMutableURLRequest(URL: fullNsurl)
    //add header
//    mutableUrlReq.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    mutableUrlReq.addValue("application/json", forHTTPHeaderField: "Content-Type")
    mutableUrlReq.addValue("application/json", forHTTPHeaderField: "Accept")

    do {
        let response: AutoreleasingUnsafeMutablePointer<NSURLResponse? >= nil
        let respJsonData: NSData =  try NSURLConnection.sendSynchronousRequest(mutableUrlReq, returningResponse: response)

        decodedJsonDict = JSON(data: respJsonData)
        print("decodedJsonDict=\(decodedJsonDict)")

    }catch let httpGetErr {
        print("httpGetErr=\(httpGetErr)")

        decodedJsonDict = nil
    }
即可。

转载请注明:在路上 » [已解决]swift 给NSURLConnection NSURLRequest添加header

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
58 queries in 0.240 seconds, using 18.82MB memory