0

我需要将数组转换为 json 并将其作为 url 中的参数与其他参数一起发送。我使用 jsonKit 进行 json 转换和 AFNetworking 进行网络通信。但它总是在服务器的 json 中给出异常。

这是用于儿子转换的代码:

NSString *jsonData = [self.finalArray JSONString];
NSString *data = [NSString stringWithFormat:@"%s",[jsonData UTF8String] ];

该数据最终作为 url 中的参数发送。网络通信代码:

postData=[postData stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *requestUrl = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@%@",url,postData]];
NSURLRequest *request =[[NSURLRequest alloc] initWithURL:requestUrl];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

[operation setCompletionBlockWithSuccess:success failure:failure];
[operation start]; 

也用于转义字符:

[postData stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

收到错误:

错误域=NSURLErrorDomain 代码=-1002“不支持的 URL”UserInfo={NSUnderlyingError=0x7d51e9a0 {错误域=kCFErrorDomainCFNetwork 代码=-1002“不支持的 URL”UserInfo={NSLocalizedDescription=不支持的 URL}},NSLocalizedDescription=不支持的 URL}

4

1 回答 1

-1

我认为你应该这样使用它

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *strURL = [NSString stringWithFormat:@"%@/add-product.php", apiPrefix];

[manager POST:strURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictData options:0 error:&error]; // dictData is your dictionary
    NSAssert(jsonData, @"Failure building JSON: %@", error);

    NSDictionary *jsonHeaders = @{@"Content-Disposition" : @"form-data; name=\"data\""}; // data is your parameter name in which you have to pass the json

    [formData appendPartWithHeaders:jsonHeaders body:jsonData];
}

success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    NSLog(@"JSON: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
    NSLog(@"Error: %@", error);
}];

希望这会有所帮助....

于 2015-11-23T12:34:26.480 回答