我有一个与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代码或下一步的故障排除步骤有什么帮助?
答案 0 :(得分:0)
这里的问题是Web服务(基于azure,c#构建)允许将值发送到集合(字典,字典数组)之外。我们必须对其进行调整以接收Json对象而不是原始字符串。不确定是否可以在Swift中序列化非键值对,但是两种语言现在都可以与Web api一起使用。