簡體   English   中英

嘗試在Swift中復制C#POST調用

[英]Trying to replicate C# POST call in Swift

我有一個與C#客戶端一起使用的簡單Web服務,但是當我嘗試通過Swift客戶端進行POST時,拋出400狀態代碼。

到目前為止,我可以在Swift中獲得一系列檢查清單對象,它們以以下JSON格式返回:

data - - - Optional(["User": {
    "Display_Name" = "<null>";
    Email = "<null>";
    "First_Name" = "Tester 0";
    "Last_Name" = McTesterson;
    Phone = "<null>";
    "User_ID" = 1;
}, "Checklist_ID": 1, "Description": {
    "Description_ID" = 1;
    Summary = "test summary";
    Title = "Test Title u.u";
}, "Status": {
    State = 1;
    "Status_ID" = 1;
}])

當我轉到POST一個新的清單時,標題在.../checklist/create/之后的請求URI中傳遞,並且http正文/內容是“摘要”字段的單個值。 使用以下代碼在C#中成功做到了:

public static void CreateChecklist(string title, string summary = "")
{
    let url = $"/checklist/create/{title}/"
    Post<string, string>(HttpMethod.Post, url, requestContent: summary);
}

private R Post<T, R>(HttpMethod ClientMethod, string methodUrl, object requestContent = default(object))
{
    var httpClient = new HttpClient();
    methodUrl = CHECKLIST_URL + methodUrl;
    var request = new HttpRequestmessage() 
    {
        RequestUri = new Uri(methodUrl),
        Method = ClientMethod
    };

    // When uploading, setup the content here...
    if (ClientMethod == HttpMethod.Post || ClientMethod == HttpMethod.Put)
    {
        string serializedContent = JsonConvert.SerializeObject(requestContent);
        request.Content = new StringContent(serializedContent, Encoding.UTF8, "application/json");
    }

    // Process the response...
    HttpResponseMessage response;
    try 
    {
        response = httpClient.SendAsync(request).Result;
    }
    catch (Exception ex)
    {
        while (ex.InnerException != null) ex = ex.InnerException;
        throw ex;
    }

    if (response.IsSuccessStatusCode) 
    {
        var tempContent = response.Content.ReadAsStringAsync().Result;
        var r = JsonConvert.DeserializeObject<R>(tempContent);
        return r;
    }
    else 
    {
        throw new Exception("HTTP Operation failed");
    }
}

但是,當我在Swift中發帖時,會返回400響應,並且不會創建新的清單(請參見下面的控制台輸出)。 這是我正在使用的Swift代碼(合並為一個方法):

    func uglyPost<T: RestCompatible>(request: String,
                                     for rec: T,
                                     followUp: OptionalBlock = nil) {

        guard let url = URL(string: request) else { followUp?(); return }
        let g = DispatchGroup()

        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        // This is where the summary field is serialized and injected...
        do {
            let body = ["Summary": ""]
print("   isValid - \(JSONSerialization.isValidJSONObject(body))")
            request.httpBody = try JSONSerialization.data(withJSONObject: body,
                                                          options: [])
            request.setValue("application/json; charset=utf-8",
                             forHTTPHeaderField: "Content-Type")
        } catch {
            print(" Error @ CanSerializeJSONRecord")
        }

        // This is the actual POST request attempt...
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
print(" d - \n\(String(describing: data?.description))")
print(" r - \n\(String(describing: response))")
            g.leave()
            if let error = error {
                print(" Error @ CanMakePostRequest - \(error.localizedDescription)")
                return
            }
        }

        // This is where asyncronous POST reequest is executed...
        g.enter()
        task.resume()

        // Waiting for POST request to conclude before completion block
        g.wait()
        followUp?()
    }

另外,控制台輸出:

 --http://-----.azurewebsites.net/api/-----/checklist/create/SwiftPostTests
   isValid - true
 d - 
Optional("33 bytes")
 r - 
Optional(<NSHTTPURLResponse: 0x7fb549d0e300> { URL: http://-----.azurewebsites.net/api/-----/checklist/create/SwiftPostTests } { Status Code: 400, Headers {
    "Content-Type" =     (
        "application/json; charset=utf-8"
    );
    Date =     (
        "Sat, 08 Dec 2018 22:57:50 GMT"
    );
    Server =     (
        K-----
    );
    "Transfer-Encoding" =     (
        Identity
    );
    "X-Powered-By" =     (
        "ASP.NET"
    );
} })
 fulfilling
/Users/.../SingleSequenceUglyPost.swift:79: error: -[*.SingleSequenceUglyPost testUglyFullSequence] : XCTAssertGreaterThan failed: ("307") is not greater than ("307") - 

我的URI是正確的,並且服務器已啟動,因為我成功進行了GET調用,並且可以從C#客戶端進行POST。 為什么我要獲取400代碼或下一步的故障排除步驟有什么幫助?

這里的問題是Web服務(基於azure,c#構建)允許將值發送到集合(字典,字典數組)之外。 我們必須對其進行調整以接收Json對象而不是原始字符串。 不知道是否可以在Swift中序列化非鍵值對,但是兩種語言現在都可以與Web api一起使用。

暫無
暫無

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

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