Sending an HTTP POST request on iOS

前端 未结 7 990
梦谈多话
梦谈多话 2020-11-22 12:04

I\'m trying to send an HTTP Post with the iOS application that I\'m developing but the push never reaches the server although I do get a code 200 as response (from the urlco

相关标签:
7条回答
  • 2020-11-22 12:30

    Sending an HTTP POST request on iOS (Objective c):

    -(NSString *)postexample{
    
    // SEND POST
    NSString *url = [NSString stringWithFormat:@"URL"];
    NSString *post = [NSString stringWithFormat:@"param=value"];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"POST"];
    [request setURL:[NSURL URLWithString:url]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSError *error = nil;
    NSHTTPURLResponse *responseCode = nil;
    
    //RESPONDE DATA 
    NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
    
    if([responseCode statusCode] != 200){
        NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
        return nil;
    }
    
    //SEE RESPONSE DATA
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    
    return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
    }
    
    0 讨论(0)
  • 2020-11-22 12:35
    -(void)sendingAnHTTPPOSTRequestOniOSWithUserEmailId: (NSString *)emailId withPassword: (NSString *)password{
    //Init the NSURLSession with a configuration
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    //Create an URLRequest
    NSURL *url = [NSURL URLWithString:@"http://www.example.com/apis/login_api"];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    //Create POST Params and add it to HTTPBody
    NSString *params = [NSString stringWithFormat:@"email=%@&password=%@",emailId,password];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
    
    //Create task
    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //Handle your response here
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
         NSLog(@"%@",responseDict);
    }];
       [dataTask resume];
    }
    
    0 讨论(0)
  • 2020-11-22 12:36

    I am not really sure why, but as soon as I comment out the following method it works:

    connectionDidFinishDownloading:destinationURL:
    

    Furthermore, I don't think you need the methods from the NSUrlConnectionDownloadDelegate protocol, only those from NSURLConnectionDataDelegate, unless you want some download information.

    0 讨论(0)
  • 2020-11-22 12:43

    The following code describes a simple example using POST method.(How one can pass data by POST method)

    Here, I describe how one can use of POST method.

    1. Set post string with actual username and password.

    NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"]; 
    

    2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    

    You need to send the actual length of your data. Calculate the length of the post string.

    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 
    

    3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest object and initialize it.

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    

    Set the Url for which your going to send the data to that request.

    [request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]]; 
    

    Now, set HTTP method (POST or GET). Write this lines as it is in your code.

    [request setHTTPMethod:@"POST"]; 
    

    Set HTTP header field with length of the post data.

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    

    Also set the Encoded value for HTTP header Field.

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    

    Set the HTTPBody of the urlrequest with postData.

    [request setHTTPBody:postData];
    

    4. Now, create URLConnection object. Initialize it with the URLRequest.

    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    

    It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.

    if(conn) {
        NSLog(@"Connection Successful");
    } else {
        NSLog(@"Connection could not be made");
    }
    

    5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.

    // This method is used to receive the data which we get using post method.
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
    
    // This method receives the error report in case of connection is not made to server. 
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
    
    // This method is used to process the data after connection has made successfully.
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    

    Also Refer This and This documentation for POST method.

    And here is best example with source code of HTTPPost Method.

    0 讨论(0)
  • 2020-11-22 12:43

    Using Swift 3 or 4 you can access these http request for sever communication.

    // For POST data to request

     func postAction()  {
    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
    let parameters = ["id": 13, "name": "jack"] as [String : Any]
    //create the url with URL
    let url = URL(string: "www.requestURL.php")! //change the url
    //create the session object
    let session = URLSession.shared
    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
    } catch let error {
        print(error.localizedDescription)
    }
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            return
        }
        guard let data = data else {
            return
        }
        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                // handle json...
            }
        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume() }
    

    // For get the data from request

    func GetRequest()  {
        let urlString = URL(string: "http://www.requestURL.php") //change the url
    
        if let url = urlString {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print(error ?? "")
                } else {
                    if let responceData = data {
                        print(responceData) //JSONSerialization
                        do {
                            //create json object from data
                            if let json = try JSONSerialization.jsonObject(with:responceData, options: .mutableContainers) as? [String: Any] {
                                print(json)
                                // handle json...
                            }
                        } catch let error {
                            print(error.localizedDescription)
                        }
                    }
                }
            }
            task.resume()
        }
    }
    

    // For get the download content like image or video from request

    func downloadTask()  {
        // Create destination URL
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
        let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
        //Create URL to the source file you want to download
        let fileURL = URL(string: "http://placehold.it/120x120&text=image1")
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
        let request = URLRequest(url:fileURL!)
    
        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }
    
                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                } catch (let writeError) {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                }
    
            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "");
            }
        }
        task.resume()
    
    }
    
    0 讨论(0)
  • 2020-11-22 12:45

    Objective C

    Post API with parameters and validate with url to navigate if json
    response key with status:"success"

    NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
        NSLog(@"%@",string);
        NSURL *url = [NSURL URLWithString:string];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        NSURLResponse *response;
        NSError *err;
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
        NSLog(@"responseData: %@", responseData);
        NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"responseData: %@", str);
            NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                             options:kNilOptions
                                                               error:nil];
        NSDictionary* latestLoans = [json objectForKey:@"status"];
        NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
        NSString *str3=@"success";
        if ([str3 isEqualToString:str2 ])
        {
            [self performSegueWithIdentifier:@"move" sender:nil];
            NSLog(@"successfully.");
        }
        else
        {
            UIAlertController *alert= [UIAlertController
                                     alertControllerWithTitle:@"Try Again"
                                     message:@"Username or Password is Incorrect."
                                     preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action){
                                                           [self.view endEditing:YES];
                                                       }
                                 ];
            [alert addAction:ok];
            [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
            [self presentViewController:alert animated:YES completion:nil];
            [self.view endEditing:YES];
          }
    

    JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code

    **

    0 讨论(0)
提交回复
热议问题