我正在尝试在swift中发布请求。我在Objective-C中成功但是使用swift我无法发送请求。 PHP中的$emailOK
无法获取信息。问题出在哪儿?谢谢你的帮助。这里是快速代码
func httpPost1(url:String, postData: String, completion: String -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
let postString = postData
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
这里是执行代码
httpPost1("xxxxx", postData: "emailOK=Hello") { result in
print(result)//result is your string-response from server
}
这是我的PHP代码
<?php
$link = mysqli_connect($dbhost, $username, $dbpass, $database);
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
$emailOK = isset($_GET["emailOK"]) ? $_GET["emailOK"] : '';
echo $emailOK;
$query = "INSERT INTO UserInfo VALUES ('', '$emailOK')";
mysqli_query($link, $query) or die (mysqli_error("error"));
mysqli_close($link);
?>
答案 0 :(得分:1)
我找到了问题,感谢@OOPer评论。问题出在PHP $emailOK = isset($_GET["emailOK"]) ? $_GET["emailOK"] : '';
中,应该是$emailOK = $_POST['emailOK'];
答案 1 :(得分:0)
尝试使用此代码创建会话对象。我不确定这是否能完全解决你的问题,但我认为你应该试一试。
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
答案 2 :(得分:0)
如果您需要将电子邮件作为网址的一部分发送,则应将其包含在网址中:
vm.type = getFromURL('what=') || 'Events';
function getFromURL(filterName){
var url = $location.url();
// if there is already a hash in the url
if(url && url.indexOf('params?') >= 0){
// If the search param already exists
if(url.indexOf(filterName) >= 0){
// Split url at already existing search param
var searchParams = url.split(filterName)[1];
// if there is still an '&' in the url do something
if(searchParams.indexOf('&') >= 0){
// split at the '&' and get rid of anything after it(other search params)
var singledParam = searchParams.split('&')[0];
return singledParam;
}else{
return searchParams;
}
// If the suggested search param doesn't exist
}
}
}
但是由于您发送的是POST请求,因此通常会在HTTP正文中发送。相当常见的方式是以JSON格式发送它:
var requestURL = url + "?" + postData
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
答案 3 :(得分:0)
如果您不想花费大量时间无用地编写成功的获取/发布请求,那么您最好选择使用所需的所有方法来使用库。
以我的拙见,我建议你 Alamofire https://github.com/Alamofire/Alamofire
否则,要成功完成您的请求,您应指定 Content-Type , Content-Type 标题信息
希望这会对你有所帮助。
答案 4 :(得分:0)
let dict = ["emailOK" : "Hello"]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
let request = NSMutableURLRequest(URL: NSURL(string:"url")!)
request.HTTPMethod = "POST"
let postString = jsonString
request.HTTPBody = postString.dataUsingEncoding(NSASCIIStringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}