最新消息:VPS服务器又从fzhost.net换回Linode了,主题仍用朋友推荐的大前端D8

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

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
13 queries in 0.192 seconds, using 9.91MB memory