从Swift到Apache / PHP进行简单的POST请求。
Swift代码:
let request = NSMutableURLRequest(URL: NSURL(string: "http://dzr.lenyapugachev.ru/createMember")!)
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()
PHP:
<?php
echo $_SERVER['REQUEST_METHOD']."\n";
var_dump($_POST);
?>
输出:
GET
array(0) {}
因此,它不会充当服务器的POST。我也试过Alamofire和SwiftHTTP,效果相同。
请,好人,帮助。
答案 0 :(得分:0)
检查你的网址 对于PHP服务器,它应该是.Php文件
用作
let request = NSMutableURLRequest(URL: NSURL(string: "http://dzr.lenyapugachev.ru/createMember.php")
!)
如果你发送参数你的php服务器请求
let request = NSMutableURLRequest(URL: NSURL(string: "http://dzr.lenyapugachev.ru/createMember.php?id=13&name=Jack")!)
参考本教程,它包括php和D swift代码,以发送帖子请求TUTORIAL: POST TO WEB SERVER API IN SWIFT USING NSURLCONNECTION
答案 1 :(得分:0)
这确实是一个HTTP POST请求。您的代码没有错。使用Charles(HTPP调试代理),我看到您的请求被重定向(301 HTTP)
您需要修复服务器的代码/ .httpaccess配置
请求:
POST /createMember HTTP/1.1
Host dzr.lenyapugachev.ru
Accept-Encoding gzip, deflate
Content-Type application/x-www-form-urlencoded
Content-Length 15
Accept-Language en-us
Accept */*
Connection keep-alive
User-Agent 29530174/1 CFNetwork/711.2.23 Darwin/13.4.0
响应:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://dzr.lenyapugachev.ru/createMember/">here</a>.</p>
</body></html>