我正在创建一个swift应用程序,在那里我需要将数据发布到我自己的web服务器。
目前,我的swift代码是这样的。
fileprivate class AlamofireHelper {
static var Manager : Alamofire.SessionManager = {
// Create the server trust policies
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"192.168.1.243": .disableEvaluation
]
// Create custom manager
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
let man = Alamofire.SessionManager(
configuration: URLSessionConfiguration.default,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
return man
}()
}
class UploadHelper
{
private var _postData = [String:Any]()
private let almoHelper = AlamofireHelper.Manager
init(username:String) {
_postData["username"] = username
print("Setup")
submitRequest()
}
func submitRequest()
{
print("Data is: \(_postData)")
almoHelper.request("http:/192.168.1.243/networkStorage", method: .post, parameters: _postData, encoding: JSONEncoding.default).responseString { (responce) in
print("Responce: \(responce)")
}
}
}
菲律宾比索:
<?php
echo "POST: " . var_dump($_POST) . "\n\n\n\n";
echo "GET: " . var_dump($_GET);
?>
唯一的问题是,当我运行swift代码
let helper = UploadHelper(username: iProgram)
时,从我的PHP脚本得到以下响应:Data: ["username": "iProgram"]
Responce: SUCCESS: array(0) {
}
POST:
array(0) {
}
GET:
为什么我的POST和GET变量是空的?我知道GET是空的,因为我只发送POST数据,但是POST不应该显示“username=iProgrammer”之类的内容吗?
最后,这里是我从burp suit捕获的HTTP请求:
GET /networkStorage/ HTTP/1.1
Host: 192.168.1.243
Accept: */*
User-Agent: Network%20Storage/1 CFNetwork/808.2.16 Darwin/16.3.0
Accept-Language: en-gb
Accept-Encoding: gzip, deflate
Connection: close
编辑:
出于某种原因,当我使用下面的代码并更改PHP脚本以显示“GET”变量时,我可以看到它应该发送的数据。
almoHelper.request("http://192.168.1.243/networkStorage", method: .get, parameters: _postData).responseString { (myResponce) in
let result = myResponce.result
print("Result is: \(result.value!)")
}
这是我从burp套件中截获的请求:
GET /networkStorage/?username=iProgram HTTP/1.1
Host: 192.168.1.243
Accept: */*
User-Agent: Network%20Storage/1 CFNetwork/808.2.16 Darwin/16.3.0
Accept-Language: en-gb
Accept-Encoding: gzip, deflate
Connection: close
最佳答案
首先,var_dump
不返回任何内容,它会输出结果,因此使用
echo "POST: "; var_dump($_POST); echo "\n\n\n\n";
或
echo "POST: " . print_r($_POST, true) . "\n\n\n\n";
GET /networkStorage/ HTTP/1.1
显示您发出GET请求,而不是POST。此外,您还有错误的编码JSONEncoding.defaul
。尝试稍微更改请求代码:almoHelper.request("http:/192.168.1.243/networkStorage", method: .post, parameters: _postData, encoding: URLEncoding.httpBody).responseString { (responce) in
print("Responce: \(responce)")
}
如果这不起作用,请尝试将URL从
http:/192.168.1.243/networkStorage
更改为http:/192.168.1.243/networkStorage/
或http:/192.168.1.243/networkStorage/index.php
。这可能会解决当您向
/networkStorage
发送请求时的问题,它会向/networkStorage/
发送新请求,如从burpsuit捕获的数据所示。