Objective-C equivalent of curl request

前端 未结 2 1013
长发绾君心
长发绾君心 2020-12-09 21:36

I\'m trying to manipulate this curl request in Objective-C:

curl -u username:password \"http://www.example.com/myapi/getdata\"

I\'ve implem

相关标签:
2条回答
  • 2020-12-09 22:21

    This guide seems to do what you're looking for: http://deusty.blogspot.co.uk/2006/11/sending-http-get-and-post-from-cocoa.html

    Just as an FYI, a lot of classes accept initWithData, and NSData has a method dataWithContentsOfURL, if you want to avoid setting up NSURLConnections yourself this could be an easier way of achieving what you're looking for.

    0 讨论(0)
  • 2020-12-09 22:31

    I found that the best thing to do was to not attempt the authentication within the code and to put it straight in the URL itself. The working code looks as follows:

    NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"http://%@:%@@www.example.com/myapi/getdata", API_USERNAME, API_PASSWORD]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setURL:url];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSError *error;
    NSURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    0 讨论(0)
提交回复
热议问题