1

我正在向 php 服务器发送 base64 字符串并且它运行良好。现在我想将另一个参数作为字符串发送。谁能告诉我需要在下面的代码中添加什么代码。

下面的代码适用于单个参数。我们如何为多个参数修改它?

 NSData *data = [UIImageJPEGRepresentation(imgeview.image,90) base64Encoding];

// Create your request string with parameter name as defined in PHP file
NSString *myRequestString = [NSString stringWithFormat:@"question_image=%@",data];
myRequestString = [myRequestString stringByReplacingOccurrencesOfString:
                                             @"+" withString:@"%2B"];

// Create Data from request
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] 
                                       length:[myRequestString length]];
request = [[NSMutableURLRequest alloc] initWithURL:
    [NSURL URLWithString:@"http://192.168.0.101/Mobile_tutor/webservice/question_details.php"]];
// set Request Type
[request setHTTPMethod:@"POST"];
// Set content-type
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
// Set Request Body
[request setHTTPBody:myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest:request 
                                           returningResponse:nil 
                                                       error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] 
                                              length:[returnData length]
                                            encoding:NSUTF8StringEncoding];
NSLog(@"-------------%@",response); // here you get reasponse string
4

2 回答 2

0

对于网络操作,这些更好地支持 API,如 AFNetworking 可用的女巫工作异步和更好的处理方式

AFNetworking 教程

从这里出发

NSArray *keys = @[@"UserID", ];
NSArray *objects = @[@(userId)];

NSDictionary *parameter = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:
                            [NSURL URLWithString:BaseURLString]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                        path:@"services/UserService.svc/GetUserInfo"
                                                  parameters:parameter];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSError* error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
    if ([jsonObject isKindOfClass:[NSDictionary class]]) {
        // do what ever
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];
于 2013-11-08T09:52:33.807 回答
0

给定一个NSDictionary“参数”,其键和值都是字符串,并且每个条目都代表一个参数(名称/值),您可以定义一个辅助类别:

@interface NSDictionary (FormURLEncoded)
-(NSData*) dataFormURLEncoded;
@end

dataFormURLEncoded从字典中的给定参数返回正确编码的字符序列。

编码算法由 w3c 指定:URL-encoded form data / The application/x-www-form-urlencoded encoding algorithm

它可以实现如下:

首先,一个对参数名称和参数值分别进行编码的辅助函数:

static NSString* x_www_form_urlencoded_HTML5(NSString* s)
{
    // http://www.w3.org/html/wg/drafts/html/CR/forms.html#application/x-www-form-urlencoded-encoding-algorithm   , Editor's Draft 24 October 2013
    CFStringRef charactersToLeaveUnescaped = CFSTR(" ");
    CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?@~");
    
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                             kCFAllocatorDefault,
                                             (__bridge CFStringRef)s,
                                             charactersToLeaveUnescaped,
                                             legalURLCharactersToBeEscaped,
                                             kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

最后,dataFormURLEncoded组成编码参数的字符序列。“参数”将通过连接编码name=编码组成value

parameter := name "=" value

然后,参数列表将通过用“&”分隔参数来连接参数组成:

parameters  := parameter ["&" parameter]

它可以实现如下:

@implementation NSDictionary (FormURLEncoded)

-(NSData*) dataFormURLEncoded {
    NSMutableData* data = [[NSMutableData alloc] init];
    BOOL first = YES;
    for (NSString* name in self) {
        @autoreleasepool {
            if (!first) {
                [data appendBytes:"&" length:1];
            }
            NSString* value = self[name];
            NSData* encodedName = [x_www_form_urlencoded_HTML5(name) dataUsingEncoding:NSUTF8StringEncoding];
            NSData* encodedValue = [x_www_form_urlencoded_HTML5(value) dataUsingEncoding:NSUTF8StringEncoding];
            
            [data appendData:encodedName];
            [data appendBytes:"=" length:1];
            [data appendData:encodedValue];
            first = NO;
        }
    }
    return [data copy];
}

@end

注意:字符序列使用 Unicode UTF-8 对字符串进行编码。

例子:

给定您的参数:

NSDictionary* params = @{@"a": @"a a", @"b": @"b+b", @"c": @"ü ö"};
NSData* encodedParamData = [params dataFormURLEncoded];

现在,encodedParamData将添加到内容类型为application/x-www-form-urlencoded.

编码的参数字符串变为:

a=a+a&b=b%2Bb&c=%C3%BC+%C3%B6

于 2013-11-08T11:01:27.203 回答