簡體   English   中英

AFNetworking:從Http響應獲取JSON值

[英]AFNetworking: Get JSON Value From Http Response

我主要是一名Android開發人員,並且是IOS的新手。 我正在使用AFNetworking 1.0,因為我正在使用現有資源,並且正在發送標准的http Post請求並返回數據,如下所示:

   //Sending the post request and getting the result
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://testsite.org/mobile_app"]];
    [httpClient setParameterEncoding:AFFormURLParameterEncoding];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@"http://testsite.org/mobile_app/studentregister.php"
                                                      parameters:@{@"username":username, @"displayname":displayname, @"password":password, @"passwordc":passwordc, @"email":email, @"teacherCode":teacherCode}];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Print the response body in text
        NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation start];

根據burp西裝,響應中應包含如下所示的JSON數據:

{"userCharLimit":"Your username must be between 5 and 25 characters in length"}

{"displaynameCharLim":"Your displayname must be between 5 and 25 characters in length"}

{"passLimit":"Your password must be between 8 and 50 characters in length"}

{"emailInvalid":"Not a valid email address"}

{"teacherCodeLength":"Your teacher code is not 5 to 12 characters"}.

如何獲取這些JSON值? 我已經看過很多AFNetworking 2.0 JSON示例和發送JSON Post請求,但是我似乎可以在1.0版中找到很多東西,更不用說從標准post請求中獲取值了。 有什么想法或資源嗎?

您需要做的就是更改代碼以注冊AFJSONRequestOperation而不是AFHTTPRequestOperation。

[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

然后,您可以在AFHTTPClent上使用此方法來創建實際上為AFJSONRequestOperation類型的操作。

AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:nil failure:nil];
[httpClient enqueueOperation:operation];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM