简体   繁体   English

将curl语句转换为Objective-C

[英]Convert curl statement into Objective-C

I'm trying to use CloudApp's API ( https://github.com/cloudapp/objective-c ) to develop my app. 我正在尝试使用CloudApp的API( https://github.com/cloudapp/objective-c )开发我的应用程序。 I currently want to make it where the user can see the details of their account (eg: email, subscription details, etc.). 我目前想在用户可以看到其帐户详细信息(例如:电子邮件,订阅详细信息等)的地方进行设置。 Their API doesn't seem to work properly to do that sort of thing, but their curl example works perfectly. 他们的API似乎无法正常工作以执行此类操作,但是他们的curl示例可以完美地工作。

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

Which gets outputted to this: 哪个输出到此:

{"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}

I wanted to do something as much as the curl statement as possible. 我想做一些尽可能多的curl声明。 I looked around Google and StackOverflow and found this answer ( Objective-C equivalent of curl request ): 我环顾了Google和StackOverflow,发现了这个答案( Objective-C等同于curl请求 ):

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

I had to slightly modify it, though: 不过,我必须对其稍作修改:

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

But when I tried it, instead of getting the result of the curl statement in Terminal, I got this in the console: 但是,当我尝试它时,没有在终端中获得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>

(There's a lot more, but I won't make it long. Let me know if you need to see the full version.) (还有很多,但是我不会说太长。如果您需要完整版,请告诉我。)

I'm not too sure what to do from here. 我不太确定该怎么办。 Is there anyone that knows how to fix this? 有谁知道如何解决这个问题? Thanks in advance. 提前致谢。

A couple of thoughts 一些想法

  1. Your response is HTML: 您的回复是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> 

    This generally means that there was some problem in the request (but without seeing the full text of the HTML, it's hard to say precisely what's wrong). 通常,这意味着请求中存在一些问题(但是如果没有看到HTML的全文,很难确切地说出问题所在)。

  2. Your curl specified an Accept header of application/json , but the Objective-C example used that value for the Content-Type header. 您的curl指定了application/jsonAccept头,但是Objective-C示例使用该值作为Content-Type头。 The request isn't JSON (in this case, at least), so I suspect you meant to set the Accept header in your Objective-C code, as in the curl, not the Content-Type header. 该请求不是JSON(至少在这种情况下是JSON),因此我怀疑您打算在Objective-C代码中设置Accept标头,就像在curl中一样,而不是Content-Type标头。

  3. Your curl request specified "digest" authentication. 您的curl请求指定了“摘要”身份验证。 The CloudApp's documentation also says it uses digest authentication. CloudApp的文档还说它使用摘要身份验证。 But the Objective-C code is not doing any authentication. 但是,Objective-C代码未进行任何身份验证。

  4. You are performing synchronous network request. 您正在执行同步网络请求。 You never want to perform synchronous requests from the main thread. 您永远都不想执行来自主线程的同步请求。

You'll probably want to perform your request using NSURLSession (or if you need to support iOS versions prior to 7.0, NSURLConnection ). 您可能需要使用NSURLSession来执行请求(或者,如果您需要支持7.0之前的iOS版本,请NSURLConnection )。 This solves both points three and four, where you can perform authentication, as well perform the request asynchronously. 这解决了第三点和第四点,您可以在其中执行身份验证以及异步执行请求。 For example, with NSURLSession , you can use the authentication delegate method, while still enjoying the elegance of the completion block pattern for the request, itself: 例如,使用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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM