最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

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

Swift crifan 3406浏览 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,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.233 seconds, using 22.15MB memory