【发布时间】:2016-09-01 14:02:54
【问题描述】:
我编写此代码以通过 JSON 发送带有 2 个变量(手机号码和客户密钥)的请求,并且我想接收带有两个变量(id 和已验证)的响应,但我在读取响应时收到错误,我不知道为什么!
我在注册按钮中这部分的代码如下:
do {
let post:NSString = "dst=\(completenumber)&customer_key=\(self.CUSTOMER_KEY)"
NSLog("PostData: %@",post)
let regURL:NSURL = NSURL(string: "myreg URL here")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: regURL)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
// print(urlData)
} catch let error as NSError {
reponseError = error
urlData = nil
}
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response Data ==> %@", responseData );
//var error: NSError?
let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
let success:NSString = jsonData.valueForKey("verified") as! NSString
let resultid:NSString = jsonData.valueForKey("id") as! NSString
//[jsonData[@"success"] integerValue];
NSLog("Verified: %@", success);
NSLog("ID: %@", resultid);
if(success == "new")
{
NSUserDefaults.standardUserDefaults().setObject(resultid, forKey: "VerifiedID")
NSUserDefaults.standardUserDefaults().synchronize()
self.dismissViewControllerAnimated(true, completion: nil )
self.performSegueWithIdentifier("enter_pin", sender: self)
}
}
} else {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Registration Failed!"
alertView.message = "Connection Failure"
if let error = reponseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} catch {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Registration Failed!"
alertView.message = "Server Error!"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
错误:
Response code: 200
Response Data ==> Error
(更新)JSON 文件:
<?php
require("lib.php");
require ("src/mobile_verify_lib.php");
require_once 'plivo.php';
require_once dirname(__DIR__) . '/core/logentries/logentries.php';
date_default_timezone_set('GMT');
header('Content-Type: application/json');
if (!$_GET[customer_key])
{
echo "Error";
exit;
}
$kkey = $_GET[customer_key];
$check_customer = check_customer($kkey);
$customer_id = $check_customer[id];
$src = "19178180011";
$dst = $_GET[dst];
#$text = $_GET[text];
$pin = getpin();
$vid = generateRandomString(16);
$checktel = checktel($dst,$customer_id);
if($checktel[status])
{
#echo "You already have a pending verification request<br>";
if($_GET[clear] == "yes")
{
destroyvid($checktel[vid]);
$js[id] = $checktel[vid];
$js[verified] = "cleared";
echo json_encode($js);
exit;
}
destroyvid($checktel[vid]);
}
//Check mobile number format and type (Only Mobile type is accepted)
$test = check_mobile($dst);
if(!$test[valid])
{
$js[id] = "NONE";
$js[verified] = "INVALID";
echo json_encode($js);
#echo '{"id":"NONE","verified":"INVALID"}';
exit;
}
// End
$dateandtime = date("Y-m-d H:i:s");
$servername = "mysql.tmed.pw";
$username = "ahmad";
$password = "ahVb$4TrHA11";
$dbname = "acticonnectverify";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO phone_verification (vid, mobile_number, pin, customer_id,dateandtime) VALUES ('$vid', '$dst', '$pin', '$customer_id' , '$dateandtime')";
if ($conn->query($sql) === TRUE) {
# echo "New record created successfully";
} else {
# echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
$text = "To verfiy your mobile number, Please enter this PIN: $pin";
$js[id] = $vid;
$js[tel] = $dst;
$js[text] = "true";
$js[verified] = "new";
echo json_encode($js);
#echo '{"id":"' . $vid . '","tel":"' . $dst .'","text":true,"verified":"new"}';
sendsms($dst,$src,$text,$customer_id);
?>
【问题讨论】:
-
我用错误更新了我的帖子,但关于 JSON,它不在我身上,因为它在公司服务器端,但我在 android 应用程序中使用相同的 JSON,它可以正常工作
-
也许您的服务器需要另一个主体。请注意,“错误”不是连接错误,而是来自您的服务器的响应
-
好的,我会看到并把语法再次放在这里
-
考虑使用异步网络。同步请求会阻塞 UI 并导致糟糕的用户体验。
-
如果您不确定服务器返回的内容,您应该记录 urlData 而不是 responseData。问题可能在于创建字符串。