首页 文章

试图在Swift中复制C#POST调用

提问于
浏览
0

我有一个简单的Web服务正在使用C#客户端,但是当我尝试使用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一个新的核对清单时, Headers 在 .../checklist/create/ 后传递到请求的URI中,http body / content是'Summary'字段的单个值 . 它使用以下代码在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 . Any help on why I'm getting the 400 code or what my next troubleshooting steps should be?

1 回答

  • 0

    这里的问题是Web服务(基于azure构建,c#)允许将值发送到集合之外(字典,字典数组) . 我们必须调整它以接收Json对象而不是原始字符串 . 不确定是否可以在Swift中序列化非键值对,但这两种语言现在都适用于web api .

相关问题