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

已有代码:

    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
搜:
    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
    }
即可。


发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量