objective-c HTTP POST发送请求作为表单

时间:2017-08-24 09:12:25

标签: ios objective-c json post

我已经使用POST方法在我的应用程序中使用标题值和params来调用API。 服务器只接受格式为

的表单
"form": {
        "action" : "login",
        "user" : "311"
},

当我们使用代码时

NSString *urlString = [NSString stringWithFormat:@"%@", url_string];

NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;

NSDictionary *parameters = @{@"action": @"login", @"user": @"311"};
NSString *params = [self makeParamtersString:parameters withEncoding:NSUTF8StringEncoding];
NSData *jsonData2 = [params dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: jsonData2];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];

我的表单看起来像这样

form = {
        action = login;
        user = 311;
};

你能得到你想要的结果吗? 你能帮我解决这个问题。

7 个答案:

答案 0 :(得分:0)

如何改变这样的参数。

NSDictionary *parameters = @{@"form":@{@"action": @"login", @"user": @"311"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];

答案 1 :(得分:0)

试试这个

NSURL * url = [NSURL URLWithString:@"%@",url_string];

NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession * session = [NSURLSession sessionWithConfiguration:config];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

request.HTTPMethod = @"POST";

NSDictionary * paramters = [NSDictionary dictionaryWithObjectsAndKeys:@"login",@"action",@"311",@"user", nil]; // [NSDictionary dictionaryWithObjectsAndKeys:@"value",@"key", nil];


NSDictionary *params = @{@"form": paramters};
NSError *err = nil;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];

答案 2 :(得分:0)

尝试

NSString *urlString = [NSString stringWithFormat:@"%@", url_string];

NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;

NSDictionary *parameters = @{@"action": @"login", @"user": @"311"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: parameters options:0 error:&error];

[request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: jsonData];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];

答案 3 :(得分:0)

 NSError *error;
 NSDictionary *parameters = @{@"form": @{@"action": @"login", @"user": @"311"}};
 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters 
      options:NSJSONWritingPrettyPrinted error:&error];
 request.HTTPBody = jsonData

 //Using NSURLSession is better option than using NSURLConnection
 NSURLSession *session = [NSURLSession sharedSession];
 NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;

  if (!error && respHttp.statusCode == 200) {

    NSDictionary* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSLog(@"%@", respondData);

  } else{
    NSLog(@"%@", error);
  }
}];

[dataTask resume];

答案 4 :(得分:0)

如果您需要base64编码,请尝试此操作

NSMutableDictionary *param = [@{@"form":@{@"action": @"login", @"user": @"311"}} mutableCopy];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:serviceURL];
NSString *strEncoded = [self encodeParameters:param];
NSData *requestData = [strEncoded dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestData];
[request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)requestData.length] forHTTPHeaderField:@"Content-Length"];

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


// Function encodeParameters 

+(NSString *)encodeParameters:(NSDictionary *)dictEncode
{
// Encode character set as per BASE64
NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"/+=\n"] invertedSet];

NSMutableString *stringEncode = [[NSMutableString alloc] init];
NSArray *allKeys = [dictEncode allKeys];
for (int i = 0;i < allKeys.count; i++) {
    NSString *key = [allKeys objectAtIndex:i];
    if([dictEncode valueForKey:key])
    {
        [stringEncode appendFormat:@"%@=%@",key,[[dictEncode valueForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:URLBase64CharacterSet]];
    }

    if([allKeys count] > i+1)
    {
        [stringEncode appendString:@"&"];
    }
}

return stringEncode;
}

答案 5 :(得分:0)

试试这个,

NSString *parameters = @"\"form\":{\"action\" : \"login\", \"user\" : \"311\"}";
NSData *jsonData2 = [parameters dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: jsonData2];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];

答案 6 :(得分:0)

尝试AFNetwoking

   NSString *urlString = [NSString stringWithFormat:@"URL"];
   NSDictionary *para=  @{@"action": @"login", @"user": @"311"};
   AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   manager.responseSerializer = [AFJSONResponseSerializer serializer];
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

   [manager POST:urlString parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
                       NSLog(@"JSON: %@", responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);

    }];