gpt4 book ai didi

ios - 使用 JustHTTP 和 Alamofire 发送两次 HTTP post

转载 作者:搜寻专家 更新时间:2023-11-01 07:30:19 24 4
gpt4 key购买 nike

我正在尝试使用 iOS 9 中的 Swift 2 HTTP 上传(到 Windows IIS 服务器)图像和表单参数,由于某种原因它发送了两次帖子,即使我只是在按钮上调用函数 one点击。

我已检查该按钮未触发超过一次。

我正在使用基本身份验证发布到 HTTPS(我已尝试使用 HTTP,结果相同)。它正在使用 JustHttp(版本 0.3)和 Alamofire 3 发生。

在 Alamofire(和 JustHTTP)中观察上传进度,我可以看到它更新了 totalBytesExpectedToWrite,然后在上传的某个时刻,totalBytesExpectedToWrite 的值翻了一番。

我已经尝试调试 JustHTTP 和 Alamofire 以了解发生这种情况的原因,但无法找到它发生的位置。

我使用的 JustHttp 代码是:

Just.post(
"https://my.url.com",
auth:("xxxxxxxx", "xxxxxxxxx"),
timeout: 20,
data:["Name": tfName.text! as AnyObject,
"Email": tfEmail.text! as AnyObject,
files:[
"file":HTTPFile.Data("photo.jpg", imagedata!, nil)
],
asyncProgressHandler: {(p) in
print(p.type) // either .Upload or .Download
if (p.type == ProgressType.Upload)
{
dispatch_async(dispatch_get_main_queue()) {
// update some UI
self.textView.titleLabel.text = "Sending Entry...\(Int(p.percent*100))%"
}
}
},
asyncCompletionHandler: {(r) in
dispatch_async(dispatch_get_main_queue()) {
print(r.statusCode)
}
})

Alamofire 代码是:

Alamofire.upload(Method.POST, "https://the.url.com", multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imagedata!, name: "file", fileName: "photo.jpg", mimeType: "image/png")
multipartFormData.appendBodyPart(data: "My Name".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: "Name")
multipartFormData.appendBodyPart(data: "My Email address".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: "Email")
},
encodingCompletion: { encodingResult in
print("encoding done")
switch encodingResult {
case .Success(let upload, _, _):
upload.authenticate(user: "xxxxxx", password: "xxxxxxxxxx")
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
print("a: \(bytesWritten) b: \(totalBytesWritten) c: \(totalBytesExpectedToWrite)")

}
upload.responseString { request, response, responseBody in
print(request)
print(response!.statusCode)
switch responseBody {
case Result.Success(let responseValue):
print(responseValue)

case Result.Failure(_, let error as NSError):
print(error)

default: break

}
}
case .Failure(let encodingError):
print(encodingError)
}
})

更新:

我现在已经在没有身份验证的情况下使用 Alamofire 进行了尝试,它按预期工作,即只发送一次整个请求。

最佳答案

好的,我已经解决了这个问题。除了 auth 参数(在 Just 和 Alamofire 中)之外,我还需要添加到以下 header 中。我从 Alamofire 文档中获取了代码,但没有意识到我需要添加 header 并包含 auth 属性。

let user = "xxxxxxx"
let password = "xxxxxxx"
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]

然后对于 Alamofire:

Alamofire.upload(Method.POST, "https://my.url.com", headers: headers, multipartFormData: [...]

对于 JustHttp:

Just.post("https://my.url.com",
auth:(user, password),
headers: headers,
[...]

为了完整起见,远程网络服务器是运行 Asp.Net C# MVC 5 的 IIS 7.5,具有以下 Auth 操作过滤器:

public class BasicAuthenticationAttribute : ActionFilterAttribute
{
public string BasicRealm { get; set; }
protected string Username { get; set; }
protected string Password { get; set; }

public BasicAuthenticationAttribute(string username, string password)
{
this.Username = username;
this.Password = password;
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"];
if (!String.IsNullOrEmpty(auth))
{
var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
var user = new { Name = cred[0], Pass = cred[1] };
if (user.Name == Username && user.Pass == Password) return;
}
var res = filterContext.HttpContext.Response;
res.StatusCode = 401;
res.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "content.imaginecruising.co.uk"));
res.End();
}
}

C# MVC 用法:

[BasicAuthenticationAttribute("myusername", "mypassword", BasicRealm = "my.domain.com")]
public ActionResult MyAction()
{

关于ios - 使用 JustHTTP 和 Alamofire 发送两次 HTTP post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32892739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com