Simple http post example in Objective-C?

后端 未结 8 1481
谎友^
谎友^ 2020-11-28 01:32

I have a php webpage that requires a login (userid & password). I have the user enter the information into the app just fine.. but I need an example on how to do a POST

8条回答
  •  醉话见心
    2020-11-28 02:21

     NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
    [contentDictionary setValue:@"name" forKey:@"email"];
    [contentDictionary setValue:@"name" forKey:@"username"];
    [contentDictionary setValue:@"name" forKey:@"password"];
    [contentDictionary setValue:@"name" forKey:@"firstName"];
    [contentDictionary setValue:@"name" forKey:@"lastName"];
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data
                                              encoding:NSUTF8StringEncoding];
    NSLog(@"%@",jsonStr);
    
    NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
       [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    
    [request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success: failure:];
    

提交回复
热议问题