用swift发送http请求

时间:2016-02-26 15:21:02

标签: 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.}

2 个答案:

答案 0 :(得分:0)

马科,

不要使用NSMutableURLRequests,使用会话...... 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()

}

答案 1 :(得分:0)

Marco,

我建议使用alamofire

看一下这个例子

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization

             if let JSON = response.result.value {
                 print("JSON: \(JSON)")
             }
         }

非常简单,序列化工作正常

您可以将pod安装在一行中。