来自iOS的自定义HTTP请求被拒绝

时间:2015-05-23 15:45:21

标签: ios swift http

我正在尝试向iOS上的php脚本发送HTTP请求。我使用multipart / form-data,因为我还需要能够发送JPEG。用户代理每次都是curl在终端工作中从curl发送请求。以下是我最终根据下面的代码生成的请求。

POST /Folder/GetData.php HTTP/1.1
Host: website_goes_here
Content-Type: multipart/form-data; boundary=This12@
Expect: 100-continue
Content-Length: 146
Accept: */*
User-Agent: curl/7.37.1
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: keep-alive


--This12@
Content-Disposition: form-data; name=uname

ThisIsTheUserNameHere
--This12@
Content-Disposition: form-data; name=pass

PasswordGoesHere
--This12@--

这是我用来生成此请求的快速代码(数据是一个使用字典数组发送到函数的变量。):

var request=NSMutableURLRequest(URL: NSURL(string: “website-HERE”)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 60)
request.timeoutInterval=NSTimeInterval(60)
request.HTTPMethod="POST";
var end="This12@";

request.addValue("multipart/form-data; boundary="+end, forHTTPHeaderField: "Content-Type")
request.setValue("*/*" , forHTTPHeaderField: "Accept")
request.setValue("close" , forHTTPHeaderField: "Connection")
request.setValue("100-continue", forHTTPHeaderField: "Expect")
request.setValue("curl/7.37.1", forHTTPHeaderField: "User-Agent")
var body=NSMutableData()

body.appendData(("\r\n--"+end+"\r\n").dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!)
var first=true
for object in data{
    if !(first){
        body.appendData(("\r\n--"+end+"\r\n").dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!)
    }
    first=false
    if((object[“Content-Type”] as! String)=="text/plain"){
    body.appendData(("Content-Disposition: form-data; name="+(object[“name”] as! String)+"\r\n\r\n"+(object[“TextToSend”] as! String)).dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!)
    }else{
        var part1="Content-Disposition: attatchment; name="+(object[“name”] as! String)
        var part2="; filename="+(object[“FileName”] as! String)+";\r\nContent-Type: "
        body.appendData((part1+part2+(object[“Content-Type”] as! String)+"\r\n\r\n").dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!)
        body.appendData(object[“Data”] as! NSData);

    }



}
body.appendData(("\r\n--"+end+"--\r\n").dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!)
request.HTTPBody=body

我的GoDaddy网站会在最初几次返回有效的响应,然后连接开始在下一分钟重置,这会重复。这有什么理由吗?请回复代码或HTTP请求的更正。如果这有帮助,则使用以下命令发送连接:

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) ->
        Void in
println(NSString(data: data, encoding: NSASCIIStringEncoding));
}

谢谢,

2 个答案:

答案 0 :(得分:0)

您不会显示实际发送请求和处理响应的代码。

我的猜测是,你没有读到响应的结尾,所以连接没有被关闭。这将让你有很多连接保持打开,直到GoDaddy决定扼杀你。

答案 1 :(得分:0)

It turns out that GoDaddy has a post limit per ip in a certain amount of time. Shared Hosting plans have a limit.