开发者

Creating a POST/GET request using Objective -C [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Tutorials for using HTTP POST and GET on the iPhone in Objective-C

Is there away to create an NSArray with the correct information like id = 1, name = @"John", score = 100 then send it and receive a response from the server?

Maybe display it inside an NSLog();

Can anyone help answer this question by linking me to a good tutorial, I don't want to use ASIHTTPRequest either. I know it would be much simpler but if there is away to do something without using a load of prewritten code id rather learn how to make something using the functionality the the foundation framewor开发者_StackOverflowk offers before going off using someone elses classes.


What you're looking for is NSMutableURLRequest and the addValue:forHTTPHeaderField method.

Create the request with the URL you wish to communicate with. Load the values you wish to transmit into the header or into the HTTPBody, set your HTTPMethod and then use a NSURLConnection method to send and receive the response.

As for an array with the information you could simply enumerate through the array and add the values to the HTTPHeaderFields. It really depends on what the server is setup to receive.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i

Has more information.

NSString *urlString = @"http://yoururl.com";
NSURL *url = [NSUL URLWithString:urlString];
NSMutalbeURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSDictionary *headerInformation = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"John",@"name",@"100",@"score", nil];
for (NSString *key in [headerInformation allKeys])
    {
        [request addValue:[dict valueForKey:key] forHTTPHeaderField:key];
    }
    NSHTTPURLResponse *response = nil;
    NSError *error = nil;
    // this will perform a synchronous GET operation passing the values you specified in the header (typically you want asynchrounous, but for simplicity of answering the question it works)
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request reuturningResponse:&response error:&error];
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Response: %@", responseString);
    [responseString release];


It might be easier to just use NSData to send a url request and store the response then to reinvent the wheel. Here is some code similar to something in my production project:

+ (NSData *)getProfiles {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];

    //  Create string of the URL
    NSString *serviceURL = [NSString stringWithFormat:@"http://www.myurlhere.com/getProfiles.php?token=%@", token];
    NSLog(@"Service URL : %@", serviceURL);

    //  Create a NSURL out of the string created earlier.  Use NSASCIIStringEncoding to make it properly URL encoded (replaces " " with "+", etc)
    NSURL *URL = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

    //  Request the url and store the response into NSData
    NSData *data = [NSData dataWithContentsOfURL:URL];
    if (!data) {
        return nil;
    }

    //  Since I know the response will be 100% strings, convert the NSData to NSString
    NSString *response = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];

    //  Test response and return a string that an XML Parser can parse
    if (![response isEqualToString:@"UNAUTHORIZED"]) {
        response = [response stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
        data = [response dataUsingEncoding:NSASCIIStringEncoding];
        return data;
    } else {
        return nil;
    }
}

NSLog output:

[Line: 476] +[WebSupport getProfiles]: Service URL : http://www.myurlhere.com/getProfiles.php?token=abcdef0123456789abcdef0123456789
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜