簡體   English   中英

如何在moya中傳遞帶有POST請求的JSON主體

[英]How to pass the JSON body with POST request in moya

我正在使用moya庫發出POST請求。 在Tar​​getType中,我無法看到任何屬性傳遞參數[JSON正文]和POST請求。 在這里,我附加了TargetType

public protocol TargetType {

    /// The target's base `URL`.
    var baseURL: URL { get }

    /// The path to be appended to `baseURL` to form the full `URL`.
    var path: String { get }

    /// The HTTP method used in the request.
    var method: Moya.Method { get }

    /// Provides stub data for use in testing.
    var sampleData: Data { get }

    /// The type of HTTP task to be performed.
    var task: Task { get }

    /// Whether or not to perform Alamofire validation. Defaults to `false`.
    var validate: Bool { get }

    /// The headers to be used in the request.
    var headers: [String: String]? { get }
}

public extension TargetType {
    var validate: Bool {
        return false
    }
}

最后,我得到了解決問題的方法。 在Moya 10.0中,我們可以在任務屬性[TargetType]中傳遞http body JSON有效內容。

點擊這里參考

var task: Task {
    switch self {
    case .zen, .showUser, .showAccounts: // Send no parameters
        return .requestPlain
    case let .updateUser(_, firstName, lastName):  // Always sends parameters in URL, regardless of which HTTP method is used
        return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: URLEncoding.queryString)
    case let .createUser(firstName, lastName): // Always send parameters as JSON in request body
        return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: JSONEncoding.default)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM