如何从我的简单有效的 POST 方法打印响应

How can I print the response from my simple, working POST method

我有一个 post 方法,如下所示:

NSString *totalPostURL = [NSString stringWithFormat:@"%@registerDevice",self.textUrl];

NSMutableURLRequest *request = [NSMutableURLRequest
                                    requestWithURL:[NSURL URLWithString:totalPostURL]];


NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:self.finalDict options:0 error:&error];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

代码工作正常,但我不知道如何打印此 post 的响应。欢迎提出任何建议,因为我是 iOS 开发的新手。

您在连接委托中得到了响应。寻找方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}

您可以打印如下响应:

NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

NSLog(@"Response:%@",returnString);

但是请记住,作为新手,不要忘记阅读调用 web 服务的教程。Interacting with webservices.

你可以这样使用...

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    [receivedData appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSString *jsonString = [[NSString alloc] initWithString: receivedData];

    NSData* cData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *WSerror;
    NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:cData options:NSJSONReadingAllowFragments error:&WSerror];

}

打印 responseDic。

@Ayan Khan 说的对!在这里,我为 http post 打印响应添加示例代码并尽可能解析为 JSON,它将异步处理所有内容,因此您的 GUI 将刷新得很好并且根本不会冻结 - 这很重要注意到。

//POST DATA
NSString *theBody = [NSString stringWithFormat:@"parameter=%@",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = @"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:@"%@/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:@"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(@"Trying to call ws %@",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"Download Error:%@",error.description);
    }
    if (data) {

        //
        // THIS CODE IS FOR PRINTING THE RESPONSE
        //
        NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
        NSLog(@"Response:%@",returnString);

        //PARSE JSON RESPONSE
        NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                        error:NULL];

        if ( json_response ) {
            if ( [json_response isKindOfClass:[NSDictionary class]] ) {
                // do dictionary things
                for ( NSString *key in [json_response allKeys] ) {
                    NSLog(@"%@: %@", key, json_response[key]);
                }
            }
            else if ( [json_response isKindOfClass:[NSArray class]] ) {
                NSLog(@"%@",json_response);
            }
        }
        else {
            NSLog(@"Error serializing JSON: %@", error);
            NSLog(@"RAW RESPONSE: %@",data);
            NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
            NSLog(@"Response:%@",returnString2);
        }
    }
}];

希望对您有所帮助!