Ios HTTP post使用JustHTTP和Alamofire发送了两次
我正在尝试使用iOS 9中的Swift 2通过HTTP上传(到Windows IIS服务器)一个图像和表单参数,出于某种原因,它会发送两次帖子,尽管我只需单击一个按钮即可调用函数1 我已经检查过按钮没有多次启动 我正在用basic auth发布到HTTPS(我用HTTP尝试了同样的结果)。它是使用JustHttp(版本0.3)和Alamofire 3实现的 通过观察Alamofire(和JustHTTP)中的上传进度,我可以看到它更新了Ios HTTP post使用JustHTTP和Alamofire发送了两次,ios,swift,alamofire,Ios,Swift,Alamofire,我正在尝试使用iOS 9中的Swift 2通过HTTP上传(到Windows IIS服务器)一个图像和表单参数,出于某种原因,它会发送两次帖子,尽管我只需单击一个按钮即可调用函数1 我已经检查过按钮没有多次启动 我正在用basic auth发布到HTTPS(我用HTTP尝试了同样的结果)。它是使用JustHttp(版本0.3)和Alamofire 3实现的 通过观察Alamofire(和JustHTTP)中的上传进度,我可以看到它更新了totalBytesExpectedToWrite,然后在上
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中)之外,我还需要添加到以下标题中。我从Alamofire文档中获得了代码,但没有意识到我需要添加标题并包含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,
[...]
为完整起见,远程Web服务器是运行Asp.Net C#MVC 5的IIS 7.5,具有以下身份验证操作筛选器:
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()
{
我对基本身份验证也有同样的问题,谢谢你的回答!