0

配列をjsonに変換し、それをURLのパラメーターとして他のパラメーターとともに送信する必要があります。私はjson変換にjsonKitを使用し、ネットワーク通信に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]];

受信したエラー:

エラー Domain=NSURLErrorDomain Code=-1002 "サポートされていない URL" UserInfo={NSUnderlyingError=0x7d51e9a0 {エラー Domain=kCFErrorDomainCFNetwork Code=-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 に答える