简体   繁体   English

从iOS向php Web服务发送请求

[英]Sending a request to a php web service from iOS

I have a question relating to sending a POST request from an iOS app to a web service written in php, that will ultimately query a MySQL database. 我有一个关于将POST请求从iOS应用发送到以php编写的Web服务的问题,最终将查询MySQL数据库。

tldr: How do I view the contents of the POST variables directly in the browser window, without refreshing? tldr:如何直接在浏览器窗口中查看POST变量的内容,而无需刷新?

Long version: 长版:

I had written my Swift code in Xcode, with NSURLSession, request, data etc. 我已经用Xcode编写了我的Swift代码,其中包含NSURLSession,请求,数据等。

I had a php web page set to var_dump($_POST); 我有一个PHP网页设置为var_dump($_POST); so that I could check that the data was sent in correctly (my data was a hard-coded string in Xcode for testing purposes). 这样我就可以检查数据是否正确发送(出于测试目的,我的数据是Xcode中的硬编码字符串)。

I couldn't for the life of me figure out why I kept getting empty POST variables, until I decided to add a test query statement to my web page binding the POST variable. 我一辈子都无法弄清楚为什么我一直得到空的POST变量,直到我决定在绑定POST变量的网页上添加测试查询语句。 Lo and behold, the query ran successfully and my table updated. 瞧,查询成功运行了,我的表也更新了。

I now realise that the reason I thought the POST variable was empty was because I was refreshing the web page in order to see the results of my var_dump . 现在,我意识到我认为POST变量为空的原因是因为我正在刷新网页以查看var_dump的结果。 I now also know that this was deleting the POST data, because when I repeated this action with the query statement, my table was getting NULL rows. 我现在也知道这正在删除POST数据,因为当我对查询语句重复此操作时,我的表正在获取NULL行。

My question is how do I view the contents of the POST variables directly in the browser window, without refreshing? 我的问题是如何直接在浏览器窗口中查看POST变量的内容,而无需刷新? I know this must be a real noob goose chase I've led myself on... but I am a noob. 我知道这一定是我一直以来对自己的真正菜鸟追逐……但是我是菜鸟。

Thank you 谢谢

You would need to modify the service itself to output those values in some way. 您将需要修改服务本身,以某种方式输出这些值。 If this is strictly for debugging, you are better off having the service write out to a log file instead. 如果这仅用于调试,则最好将服务写出到日志文件中。 If this is part of the requesting applications call and the data needs to be displayed to the user, the service should probably return either an XML or JSON string response that your application can parse. 如果这是请求应用程序调用的一部分,并且需要将数据显示给用户,则该服务可能应返回应用程序可以解析的XML或JSON字符串响应。 Otherwise, you can use Fiddler to monitor your web traffic. 否则,您可以使用Fiddler监视您的Web流量。

Of course overtime you refresh the page you just get an empty variable. 当然,加班您刷新页面只会得到一个空变量。 This is what I used to test if my code was working: 这是我用来测试代码是否正常工作的内容:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    testPost() // this function will test that the code is sending the variable to your server
    return true
}

func testPost() {

    let variableToPost = "someVariable"

    let myUrl = NSURL(string: "http://www.yourserver.com/api/v1.0/post.php")
    let request = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let postString = "variable=\(variableToPost)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
        { data, response, error in

            if error != nil {

                print(error)
                return

            }

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary


                if let parseJSON = json{


                    let result = parseJSON["status"] as? String
                    let message = parseJSON["message"] as? String


                    if result == "Success"{

                        //this should return your variable

                        print(message)


                    }else{

                        // print the message if it failed ie. Missing required field
                        print(message)

                    }

                }//if parse

            }  catch let error as NSError {
                print("error in registering: \(error)")


            } //catch

    }

    task.resume()
}

then your php file will only check if there is no empty post and return the variable as JSON: post.php 那么您的php文件将仅检查是否没有空的帖子,并将变量返回为JSON: post.php

<?php
$postValue = htmlentities($_POST["variable"]);

 if(empty($postValue))
 {
 $returnValue["status"] = "error";
 $returnValue["message"] = "Missing required field";
 echo json_encode($returnValue);
 return;
 } else {

 $returnValue["status"] = "success";
 $returnValue["message"] = "your post value is ".$postValue."";
 echo json_encode($returnValue);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM