How to post raw data in swift 3?

你离开我真会死。 提交于 2019-12-05 06:20:55

问题


If I post raw data using Postman, response is coming. I am using this code

 var dict = Dictionary<String, Any>()
 dict = ["user_id" :userid as AnyObject, "type" :type as AnyObject, "complaint_id" :complaintId as AnyObject,  "auth_code" : authCode as AnyObject, "isSkip" :isSkip as AnyObject]

 let url:URL = URL(string: "http://development.easystartup.org/prigovo/Backend/detailed_complaint/index.php")!
    let session = URLSession.shared

   var postData = NSData()
    do{

    postData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData!
    }catch {
        print("error")
    }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
   // request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length")
    request.setValue("text/html", forHTTPHeaderField: "Content-Type")
    request.setValue("json/application", forHTTPHeaderField: "Accept")

    request.httpBody = postData as Data

    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in

        guard let data = data, let _:URLResponse = response, error == nil else {
            print("error")
            return
        }
        let dataString =  String(data: data, encoding: String.Encoding.utf8)
        print(dataString ?? "no data")
    }
    task.resume()

Getting data of 0 bytes everyTime. Already tried with Alamofire but no response.

Also I tried in Objective C where I am getting response, code is :

  NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)postData.length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSError *error = nil;
    NSHTTPURLResponse *response = nil;


    [[NSURLConnection alloc] initWithRequest:request delegate:self];


    NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error)
    {
        //error
        NSLog(@"error");
        return @"";
    }
    else
    {
        NSLog(@"No error");
        NSString *charlieSendString = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
        NSLog(@"data come : %@",charlieSendString);
        return charlieSendString;
    }

Posted "dict" in Log :

["complaint_id": COMBRD1, "user_id": USR9, "type": complaint_brand, "auth_code": KL1hwYrAhNVnSgT, "is_skip": 2]


回答1:


var dict = Dictionary<String, Any>()

    dict = ["user_id" :userid, "type" :type, "complaint_id" :complaintId,"auth_code" : authCode, "is_skip" :isSkip]
    var  jsonData = NSData()

   // var dataString2 :String = ""
    do {
         jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) as NSData
        // you can now cast it with the right type
    } catch {
        print(error.localizedDescription)
    }


    let url:URL = URL(string: "http://Backend/detailed_complaint/index.php")!
    let session = URLSession.shared


    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData as Data

    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in

        guard let data = data, let _:URLResponse = response, error == nil else {
            print("error")
            return
        }
        let dataString =  String(data: data, encoding: String.Encoding.utf8)
        print("no data",dataString ?? "no data")
    }
    task.resume()


来源:https://stackoverflow.com/questions/43092343/how-to-post-raw-data-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!