php - 快速发送http请求

标签 php swift http request

我正在尝试使用 swift 向 PHP 服务器发送 http 请求。我设法发送数据并读取服务器的响应。我只希望我的 php 服务器根据 json 请求中存在的请求类型执行不同的操作

这是我发送请求的方法:

func sendHttpRequests(data : Dictionary<String, AnyObject>) //-> NSDictionary
{
    let url = NSURL ( string : "http://aaa.bbb.ccc.ddd")!
    let request:NSMutableURLRequest = NSMutableURLRequest(URL : url)

    let payload1 = "\"r\":\"login\""
    request.HTTPMethod = "POST"

    request.HTTPBody = payload1.dataUsingEncoding(NSUTF8StringEncoding);


    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
        {
            (response, data, error) in

            if let httpResponse = response as? NSHTTPURLResponse {
                let responseCode = httpResponse.statusCode
                print("Request Status \(responseCode)")
            }
            do
            {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

                print("Json received \(json)")

                if let currItem = json["myKey"] as? String
                {
                    print(currItem)
                }
            }
            catch
            {
                print("error: \(error)")
            }
    }
}

当我用这个 php 脚本发回响应时,我成功地收到了响应:

<?php
$arr = array("myKey" => "myValue");
echo json_encode($arr);
?>

相反,当我尝试这样的事情时:

<?php
$postVar = $_POST['r'];

if (!empty($postVar)) 
{
     $arr = array("status" => "it's ok");
     echo json_encode($arr);
}
else
{
     $arr = array("status" => "something wrong");
     echo json_encode($arr);
}
?>

我收到这个错误:

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

最佳答案

马可,

不要使用 NSMutableURLRequests,使用 session ...前者已被 Apple 弃用。

这是一个例子..

func getMetaData(lePath:String, completion: (string: String?, error: ErrorType?) -> Void) {
// **** get_metadata ****
    let request = NSMutableURLRequest(URL: NSURL(string: "https://api.dropboxapi.com/2/files/get_metadata")!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    request.addValue("Bearer ab-blah", forHTTPHeaderField: "Authorization")
    request.addValue("application/json",forHTTPHeaderField: "Content-Type")
    request.addValue("path", forHTTPHeaderField: lePath)
    let cursor:NSDictionary? = ["path":lePath]
    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(cursor!, options: [])
        request.HTTPBody = jsonData
        print("json ",jsonData)
    } catch {
        print("snafoo alert")
    }

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if let error = error {
            completion(string: nil, error: error)
            return
        }
        let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("Body: \(strData)\n\n")
        do {
            let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers);
            self.jsonParser(jsonResult,field2file: "ignore")
            for (key, value) in self.parsedJson {
                print("key2 \(key) value2 \(value)")
            }

            completion(string: "", error: nil)
        } catch {
            completion(string: nil, error: error)
        }
    })
    task.resume()

}

关于php - 快速发送http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35655440/

相关文章:

ios - 多语言 iOS 应用

http - 如何在不强制 "save as"对话框的情况下设置响应文件名

php - 为什么 PHP 使用操作码缓存而 Java 编译为字节码文件?

php - 将 MySQL 字段中的所有值设置为 0

ios - Swift - 从完成 block 中解散 View Controller

ios - 如何让自定义导航 Controller 为每个 Storyboard提供相同的自定义导航栏按钮

http - 让 Varnish 忽略带有 Cookie header 的请求

http - 在代号一中使用与 GET/POST 不同的动词发送 HTTP 查询?

需要PHP脚本创建日历表或jquery完整解决方案

php - 用于目录导入的永久表与临时表