繁体   English   中英

Objective-C HTTP POST发送请求的形式

[英]objective-c HTTP POST send request as form

我已经使用POST方法在应用程序上调用带有标头值和参数的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;
};

您能否产生想要的结果? 您能帮我解决这个问题吗?

如何更改这样的参数。

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];

尝试这个

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];

尝试

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];
 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];

如果需要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;
}

尝试这个,

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];

尝试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);

    }];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM