如何通过身份验证快速发出http请求?

时间:2019-05-20 09:39:21

标签: ios swift http request

IOS ucs

我需要通过身份验证发出http请求。 首先,我需要对以下URL进行GET: http://209.97.133.56/api/ucs 但是我需要通过身份验证。 为此,我需要将Follow令牌放在某些标题中

  

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjQ2Yjg2ZDNlZDI2Y2IwOGU2NDFhZTI3NjNmMWI0ZDEwODAwZWI0M2U4YjM5MThiMTQ0YmU5YWFjMzBhNGU1ZDdhMTI4ZjA1MDI2NGNkYWZhIn0.eyJhdWQiOiIyIiwianRpIjoiNDZiODZkM2VkMjZjYjA4ZTY0MWFlMjc2M2YxYjRkMTA4MDBlYjQzZThiMzkxOGIxNDRiZTlhYWMzMGE0ZTVkN2ExMjhmMDUwMjY0Y2RhZmEiLCJpYXQiOjE1NTgzNDQ1MDIsIm5iZiI6MTU1ODM0NDUwMiwiZXhwIjoxNTg5OTY2OTAyLCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.LSsn172WUQqEzUf3wzq4lxgBL8pbKGqjJCpn0iEFPFQY6DhZCtcm4jHkqTC0FFMYrAA1n87LfdBeSvcdgWFsndD6MoKHFkZViqZXlUHDeyMmT-bVs2IrNSE9kGuaRQhz1rtys2KFbB2y4lq5w2BPhokPYvLc0nTwZ7oPTZKQlJkUi80PKDMP3LMUQpilc2cSE8FGe-d1UtMYUeseivwHcNee4knjfOUIsGl7_pV4knU6DYTWL8IMXfb3GjbBTagFRWfbjeqMMvtFVdZGfTxdeVoMqSgEQlA0W20GyJ3Ox4WuZAaODk4b7Q4cudR8vmPTSjvVU-IqB6_9wvtE3HUMEwiGazQRcmFtVqBYFPVIBHFWNBsWI2AbMxR_KSA6URzF-6qydj53yRqO41E88KQiWbHy29mb8BCoNvjR4gN9F97rE9j9Xpt-EsHK6QEqBOeoJixu8srDrgmYul4nWroRU6dQsFZjfZS4Vnm1LFF-ykOo0YVY08oRcV3LQTb8TsnS3RuQzlMifEhDajBPTsVyCyW9OkkTsi3N96E1VeRhyT0S08InczXeRV_K5BMdt7tvVAEMPoR4GCcHAR5e7924WVsbl9KmJ4itu f_FdCfBKdvcmErURIlCfZRELLC_8kNaT-04CG3Vj9_LrUb6eOcJrutawh60V_ITojWAxyF2LnQ

我来这里是为了得到一些帮助,因为我不能这样做。

import Foundation

public class UnidadeCurricularManager{
    private var ucs = [UnidadeCurricular]();


    init(){ 

        let json = "{ \"data\": [ { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18734, \"unidadeCurricularNome\": \"Algoritmos e Estruturas de Dados\", \"unidadeCurricularAbreviatura\": \"AED\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"2\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 2, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 6 }, { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18735, \"unidadeCurricularNome\": \"Programação Avançada\", \"unidadeCurricularAbreviatura\": \"PA\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"2\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 2, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 7 }, { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18735, \"unidadeCurricularNome\": \"Álgebra Linear\", \"unidadeCurricularAbreviatura\": \"AlgL\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"1\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 1, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 7 } ] }";


        //URL
        let url = URL(string: "http://http://209.97.133.56/api/ucs")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            print(String(data: data, encoding: .utf8)!)
        }

        task.resume()


        //JSON
        guard let data = json.data(using: .utf8) else {
            return
        }
        do {
            if let jsonDictionary = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
            {
                if let dataArray = jsonDictionary["data"] as? [[String:Any]] {
                    for data in dataArray {

                            let ucIdMapSiges = data["unidadeCurricularIdMapSiges"] as! Int
                            let ucNome = data["unidadeCurricularNome"] as! String
                            let ucSigla = data["unidadeCurricularAbreviatura"] as! String
                            let anoCurricularIdMapSiges = data["anoCurricularIdMapSiges"] as! Int
                            let periodoNome = data["unidadeCurricularAbreviatura"] as! String
                            let codigoEstudante = data["numeroEstudante"] as! String
                            let ects = data["numero_creditos"] as! Int


                            var uc = UnidadeCurricular (ucName: ucNome, ucSigla: ucSigla, ucIdMapSiges: ucIdMapSiges, anoCurricularIdMapSiges: anoCurricularIdMapSiges, periodoNome: periodoNome, codigoEstudante: codigoEstudante, ects: ects)

                            ucs.append(uc);
                    }
                }

            } else {
                print("bad json")
            }
        } catch let error as NSError {
            print(error)
        }

    }

    func getUcs() -> Dictionary<String, [UnidadeCurricular]> {
        var listaOfUcs = [String : [UnidadeCurricular]]()

        for u in ucs{
            if listaOfUcs[String(u.anoCurricularIdMapSiges)] != nil {
                listaOfUcs[String(u.anoCurricularIdMapSiges)]!.append(u);
            } else {
                var ucName = [UnidadeCurricular]();
                ucName.append(u);
                listaOfUcs[String(u.anoCurricularIdMapSiges)] = ucName;
            }
        }
        return listaOfUcs;
    }

}

1 个答案:

答案 0 :(得分:0)

在这里,您只需要添加Authorization的标题即可。

使用Codable进行JSON解析时,请不要使用JSONSerialization并使用此toolJson转换为struct

let url = URL(string: "http://209.97.133.56/api/ucs")!
let token = "your token"
var request = URLRequest(url: url)
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "GET"


URLSession.shared.dataTask(with: request) { (data, response , error) in
    guard let data = data else { return }
    print(String(data: data, encoding: .utf8) ?? "Invalid JSON")
}.resume()

修改

使用我提供的工具将您的json转换为由该工具转换的JSON结构

struct UPS: Codable {
    let data: [UPSData]

    enum CodingKeys: String, CodingKey {
        case data = "data"
    }
}

struct UPSData: Codable {
    let id: String
    let unidadeCurricularID: Int
    let unidadeCurricularNome: String
    let unidadeCurricularAbreviatura: String
    let unidadeCurricularAtivo: Int
    let unidadeCurricularIDMapSiges: Int
    let anoCurricularID: Int
    let anoCurricularNome: String
    let anoCurricularAbreviatura: String?
    let anoCurricularAtivo: Int
    let anoCurricularIDMapSiges: Int
    let periodoTempoID: Int
    let periodoTempoNome: String
    let periodoTempoAvreviatura: String
    let periodoTempoOrdem: Int
    let periodoTempoAtivo: Int
    let periodoTempoIDMapSiges: String
    let numeroEstudante: Int
    let idAnoLetivo: Int
    let idUnidadeCurricular: Int
    let idEstadoInscricao: Int
    let idAnoCurricular: Int
    let numeroCreditos: Int

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case unidadeCurricularID = "unidadeCurricularId"
        case unidadeCurricularNome = "unidadeCurricularNome"
        case unidadeCurricularAbreviatura = "unidadeCurricularAbreviatura"
        case unidadeCurricularAtivo = "unidadeCurricularAtivo"
        case unidadeCurricularIDMapSiges = "unidadeCurricularIdMapSiges"
        case anoCurricularID = "anoCurricularId"
        case anoCurricularNome = "anoCurricularNome"
        case anoCurricularAbreviatura = "anoCurricularAbreviatura"
        case anoCurricularAtivo = "anoCurricularAtivo"
        case anoCurricularIDMapSiges = "anoCurricularIdMapSiges"
        case periodoTempoID = "periodoTempoId"
        case periodoTempoNome = "periodoTempoNome"
        case periodoTempoAvreviatura = "periodoTempoAvreviatura"
        case periodoTempoOrdem = "periodoTempoOrdem"
        case periodoTempoAtivo = "periodoTempoAtivo"
        case periodoTempoIDMapSiges = "periodoTempoIdMapSiges"
        case numeroEstudante = "numeroEstudante"
        case idAnoLetivo = "idAnoLetivo"
        case idUnidadeCurricular = "idUnidadeCurricular"
        case idEstadoInscricao = "idEstadoInscricao"
        case idAnoCurricular = "idAnoCurricular"
        case numeroCreditos = "numero_creditos"
    }
}

在此类中添加所有网络请求代码

class NetworkRequest {


    func auth<T: Decodable>(with url: URL, token: String, completion: @escaping (T) -> Void) {

        var request = URLRequest(url: url)
        request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.httpMethod = "GET"

        URLSession.shared.dataTask(with: request) { (data, response , error) in
            guard let data = data else { return }
            do {
                completion(try JSONDecoder().decode(T.self, from: data))
            } catch let error {
                print(error)
            }
        }.resume()

    }


}

在您课堂上的任何地方使用此代码

NetworkRequest().auth(with: url, token: token) { (ups: UPS) in
    print("do what do want to you")
}