How to post data in the form of url in iOS?

时光怂恿深爱的人放手 提交于 2019-12-22 17:46:59

问题


I want to send my UITextfields data to a server.

I want to post data but the server showing error message to me.

Please check my code:

  ...

  NSURL *url=[NSURL URLWithString:@"http://projectsatseoxperts.net.au/fishing/api/postRegister.php"];

  NSString *post =[[NSString alloc] initWithFormat:@"FirstName=%@&LastName=%@userName=%@&Email=%@Phone=%@&Address=%@Password=%@&ConfirmPassword=%@",
    txt_firstname.text,txt_lastname.text,txt_username.text,txt_email.text,txt_phone.text,txt_address.text,txt_password.text,txt_confirmpassword.text];
  NSLog(@"Post is: %@",post);

  NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  NSLog(@"postData is: %@",postData); 

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

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setURL:url];
  [request setHTTPMethod:@"POST"];
  [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  //[request setValue:@"http://projectsatseoxperts.net.au/fishing/api/postRegister.php" forHTTPHeaderField:@"Content-Type"];
  [request setHTTPBody:postData];

  NSLog(@"request is: %@", [request allHTTPHeaderFields]);
  NSError *error;
  NSURLResponse *response;
  NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  NSLog(@"urlData is: %@",urlData);

  NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
  NSLog(@"%@",data);
}

After post the details the values will come here - http://projectsatseoxperts.net.au/fishing/api/register.php

Any idea or suggestions would be highly welcome.


回答1:


Your Request is proper.. just check the content Type and Encoding of your post data.. Also do consult with the server team for exact data format they expect from you..




回答2:


A couple of observations:

  1. The way you phrase your question, you would seem to be suggesting that you're trying to create a application/x-www-form-urlencoded request. If so, you should specify your Content-Type accordingly:

    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
  2. If doing a application/x-www-form-urlencoded request, then you must percent escape the data that you post, using CFURLCreateStringByAddingPercentEscapes (note, not stringByAddingPercentEscapesUsingEncoding). If any of your fields included any reserved characters, your query would fail.

    - (NSString *)percentEscapeURLParameter:(NSString *)string
    { 
        return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                         (CFStringRef)string,
                                                                         NULL,
                                                                         (CFStringRef)@":/?@!$&'()*+,;=",
                                                                         kCFStringEncodingUTF8));
    }
    
  3. Also, your post string is missing a few ampersands. I might solve this problem by using a dictionary:

    NSDictionary *dictionary = @{@"FirstName"       : txt_firstname.text,
                                 @"LastName"        : txt_lastname.text,
                                 @"userName"        : txt_username.text,
                                 @"Email"           : txt_email.text,
                                 @"Phone"           : txt_phone.text,
                                 @"Address"         : txt_address.text,
                                 @"Password"        : txt_password.text,
                                 @"ConfirmPassword" : txt_confirmpassword.text};
    

    And then build the post variable, invoking percentEscapeURLParameter for each value, like so:

    NSMutableArray *postArray = [NSMutableArray array];
    [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
        [postArray addObject:[NSString stringWithFormat:@"%@=%@", key, [self percentEscapeURLParameter:obj]]];
    }];
    NSString *post = [postArray componentsJoinedByString:@"&"];
    
  4. By the way, those field names look suspect (with lowercase "u" in "userName"; often they're all lowercase field names). Are you sure about those field names?

Beyond that, you have to show us the error that you're getting.




回答3:


Your "post" strings format look to be incorrect. You are missing some "&" in between certain fields i.e between "LastName" and "userName". Check your string as the server may not recognise the values in the string. Unless there is a specific reason for this.




回答4:


I suspect that since the API is returning XML, it is expecting XML in the HTTP POST. Contact the API developer to find out what data formats the API supports and the schema it expects.




回答5:


There a number of issues with your code:

  1. Potentially incorrect character encoding:

    In your code:

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

    you allow a lossy conversion from the character encoding of the original string to the one used for your post data. This will lead to incorrect parameters when they contain non-ASCII characters.

  2. No Content-Type header set

    Since you didn't set a content type, your data will be treated by the server as an unstructured text of ASCII characters, e.g. Content-type: text/plain; charset=us-ascii.

    You probably want to use application/x-www-form-urlencoded, or better application/json - if the server accepts that MIME type.

  3. When you set a Content-Type you also need to ensure your parameters are properly encoded according the Content-Type you set.

In order to solve these issues, I would suggest to try application/json as Content-Type and encode your parameters as JSON. Using Content-type: application/x-www-form-urlencoded is also possible, but this requires a much more elaborated encoding algorithm. Just try JSON:

So, instead of having this ugly string

NSString *post =[[NSString alloc] initWithFormat:@"FirstName=%@&LastName=%@userName=%@&Email=%@Phone=%@&Address=%@Password=%@&ConfirmPassword=%@", 
txt_firstname.text,txt_lastname.text,txt_username.text,txt_email.text,txt_phone.text,txt_address.text,txt_password.text,txt_confirmpassword.text];

create a corresponding NSDictionary object. Then serialize it to a NSData object containing the JSON using NSJSONSerialization. Use this data object for your body, and set Content-Type: application/json.



来源:https://stackoverflow.com/questions/20398194/how-to-post-data-in-the-form-of-url-in-ios

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