Objective-C equivalent of curl request

前端 未结 2 1022
长发绾君心
长发绾君心 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: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];
    

提交回复
热议问题