How to post raw data in swift 3?
Asked Answered
M

1

3

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]

Monahon answered 29/3, 2017 at 11:34 Comment(8)
It should be json/application not josn/application.Severance
@Severance Still no response :(Monahon
@DeepakChaudhary Try to set Content-Type to application/json instead of text/htmlDogtooth
@NiravD I tried both in Content-Type and Accept, still no result. Also, I tried in objectiveC, there I am getting response with all same data and headersMonahon
Can you try the objective C code with NSURLSession instead of NSURLConnection?Severance
["complaint_id": COMBRD1, "user_id": USR9, "type": complaint_brand, "auth_code": KL1hwYrAhNVnSgT, "isSkip": 2] Its not a valid json format. Please check in jsonviewer.stack.hu. I think its the dictionary log.Severance
I tried your API using Postman with following options: 1. form-data, 2. application/x-www-form-urlencoded, 3. text/plain, 4. text/html but nothing returned.Severance
All sorted, and data is coming now.. Thanks @SeveranceMonahon
M
10
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()
Monahon answered 29/3, 2017 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.