将 curl 语句转换为 Objective-C

Convert curl statement into Objective-C

我正在尝试使用 CloudApp 的 API (https://github.com/cloudapp/objective-c) 来开发我的应用程序。我目前想让用户可以看到他们帐户的详细信息(例如:电子邮件、订阅详细信息等)。他们的 API 似乎无法正常执行此类操作,但他们的 curl 示例非常有效。

curl --digest -u dev2@trijstudios.ca:trij2323 \
     -H "Accept: application/json" \
     "http://my.cl.ly/account"

输出到这个:

{"created_at":"2015-01-11T21:08:56Z","domain":null,"domain_home_page":null,"email":"dev2@trijstudios.ca","id":1778166,"private_items":true,"updated_at":"2015-01-11T21:08:56Z","activated_at":"2015-01-11T21:08:56Z","subscribed":false,"socket":{"auth_url":"http://my.cl.ly/pusher/auth","api_key":"4f6dbc3b89fa4ee9a8ff","app_id":"4721","channels":{"items":"private-items_1778166"}},"subscription_expires_at":null}

我想做一些尽可能多的curl语句。我环顾了 Google 和 Whosebug,找到了这个答案 (Objective-C equivalent of curl request):

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];

不过我不得不稍微修改一下:

NSString *apiUserName = [NSString stringWithFormat:@"dev2@trijstudios.ca"];
NSString *apiPassword = [NSString stringWithFormat:@"trij2323"];

NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"http://%@:%@@my.cl.ly/account", apiUserName, apiPassword]];
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];

NSLog(@"%@", data);

但是当我尝试它时,我没有在终端中得到 curl 语句的结果,而是在控制台中得到了这个:

<3c21646f 63747970 65206874 6d6c3e0a 0a3c6874 6d6c2078 6d6c6e73 3a6f673d 22687474 703a2f2f 6f70656e 67726170 6870726f 746f636f 6c2e6f72 672f7363 68656d61 2f222078 6d6c6e73 3a66623d 22687474 703a2f2f 7777772e 66616365 626f6f6b 2e636f6d 2f323030 382f6662 6d6c2220 6974656d 73636f70 65206974 656d7479 70653d22 68747470 3a2f2f73 6368656d 612e6f72 672f5468 696e6722 20636c61 73733d22 73717561 72657370 6163652d 64616d61 736b2220 6c616e67 3d22656e 2d434122 3e0a0a20 203c6865 61643e0a 20202020 0a202020 203c6d65 74612063 68617273 65743d22 7574662d 38223e0a 20202020 3c6d6574 61206874 74702d65 71756976 3d22582d 55412d43 6f6d7061 7469626c 65222063 6f6e7465 6e743d22 49453d65 6467652c

61676522 297c7c68 61734174 74722861 5b625d2c 22646174 612d7372 63222929 26262266 616c7365 22213d3d 67657441 74747228 615b625d 2c226461 74612d6c 6f616422 292b2222 2626496d 6167654c 6f616465 722e6c6f 61642861 5b625d29 7d696e69 7428293b 77696e64 6f772e59 55492626 5955492e 61646428 22737175 61726573 70616365 2d696d61 67656c6f 61646572 222c6675 6e637469 6f6e2861 297b7d29 3b0a7d29 28293b3c 2f736372 6970743e 0a3c7363 72697074 3e537175 61726573 70616365 2e616674 6572426f 64794c6f 61642859 293b3c2f 73637269 70743e0a 0a0a2020 20200a20 203c2f62 6f64793e 0a0a3c2f 68746d6c 3e200a>

(还有很多,但我不会写太久。如果你需要看完整版,请告诉我。)

我不太确定从这里开始做什么。有没有人知道如何解决这个问题?提前致谢。

一些想法

  1. 您的回复是HTML:

    <!doctype html>
    
    <html xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml" itemscope itemtype="http://schema.org/Thing" class="squarespace-damask" lang="en-CA">
    
      <head>
    
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,
    
    ...
    
    age")||hasAttr(a[b],"data-src"))&&"false"!==getAttr(a[b],"data-load")+""&&ImageLoader.load(a[b])}init();window.YUI&&YUI.add("squarespace-imageloader",function(a){});
    })();</script>
    <script>Squarespace.afterBodyLoad(Y);</script>
    
    
    
      </body>
    
    </html> 
    

    这一般意味着请求中存在一些问题(但没有看到HTML的全文,很难说出确切的问题)。

  2. 您的 curl 指定了 application/jsonAccept header,但 Objective-C 示例使用该值作为 Content-Type header。该请求不是 JSON(至少在这种情况下),所以我怀疑您打算在 Objective-C 代码中设置 Accept header,就像在 curl 中一样, 而不是 Content-Type header.

  3. 您的 curl 请求指定了 "digest" 身份验证。 CloudApp 的文档还说它使用摘要身份验证。但是 Objective-C 代码没有进行任何身份验证。

  4. 您正在执行同步网络请求。您永远不想从主线程执行同步请求。

您可能希望使用 NSURLSession 执行您的请求(或者如果您需要支持 7.0 之前的 iOS 版本,NSURLConnection)。这解决了第三点和第四点,您可以在其中执行身份验证以及异步执行请求。例如,使用 NSURLSession,您可以使用身份验证委托方法,同时仍然享受请求的完成块模式的优雅,本身:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
    if (challenge.previousFailureCount == 0) {
        NSURLCredential *credential = [NSURLCredential credentialWithUser:self.userid password:self.password persistence:NSURLCredentialPersistenceForSession];
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    } else {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
}

// you might have to implement the session rendition of the above authentication routine; it depends upon your server configuration; the implementation will look almost identical to the above code
//
// - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler

- (void)performQuery {
    // note, no user credentials in the URL; will be handled by authentication delegate method
    NSURL *url = [NSURL URLWithString: @"http://www.example.com/myapi/getdata"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!data) {
            NSLog(@"dataTaskWithURL error: %@", error);
            return;
        }

        NSError *parseError;
        id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
        if (responseObject) {
            // got the JSON I was expecting; go ahead and use it; I'll just log it for now
            NSLog(@"responseObject = %@", responseObject);
        } else {
            // if it wasn't JSON, it's probably some error, so it's sometimes useful to see what the HTML actually says
            NSLog(@"responseString = %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
    [task resume];
}