【问题标题】:Download an image From Craigslist从 Craigslist 下载图像
【发布时间】:2014-10-16 11:36:05
【问题描述】:

我一直在尝试从 url 下载图片(更准确地说是 Craigslist)

首先我使用了 SDWebImage 框架,但我看不到图像。之后我尝试了一个简单的方法来下载网址:

使用此网址获取图片:

http://images.craigslist.org/01212_fxFfHsZFhoi_600x450.jpg

UIImageView image;
NSString *urlstring = [NSString stringWithFormat:@"http://images.craigslist.org/01212_fxFfHsZFhoi_600x450.jpg"];
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[image setImageWithURLRequest:request
              placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                       success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
                            // Succes on loading image
                       }
                       failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
                            // Fail to load image
                       }];

我仍然无法在我的图像视图中看到图像。

问题是,如果我更改 url 并使用相同的确切代码,图像将被很好地下载。我试图在 Safari 中加载图像,它工作得很好,所以链接没问题。

例如我用过: http://monsieurstolli.files.wordpress.com/2013/10/meh.jpg

它有效。

我不知道如何下载该图像。

编辑:

我做了更多调查,我更改了代码:

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    requestOperation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Response: %@", responseObject);
        _imga.image = responseObject;

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Image error: %@", error);
    }];
    [requestOperation start];

    }

但这次我得到了以下错误:

2014-10-16 15:07:10.537 CraigslistChecker[3192:907] Image error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: not found (404)" UserInfo=0x1c5b8e30 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x1c59ac60>, NSErrorFailingURLKey=images.craigslist.org/00W0W_blCL2sqk1Jt_600x450.jpg, NSLocalizedDescription=Request failed: not found (404), com.alamofire.serialization.response.error.data=<0d0a>}
purgeIdleCellConnections: found one to purge conn = 0x1c59b1f0

【问题讨论】:

  • 请注意,“代码 sn-p”按钮用于嵌入 JavaScript,而不是用于一般代码示例。请改用“代码示例”按钮 (Ctrl-K)。

标签: ios objective-c nsurlrequest


【解决方案1】:

当我在网络浏览器中请求您发布的 URL 时,它返回 404(未找到)错误,这意味着服务器拒绝向您提供该 URL。所以要么:

  • 网址是假的
  • 图片 URL 是临时的(即将过期),在您请求之前已消失
  • 图片 URL 要求您登录(并提供错误代码)
  • 服务器通过检查引荐来源网址来防止在特定网页上下文之外加载图像。

我的猜测是最后一个。如果是这样,将 NSURLRequest 上的“Referer”(故意拼写错误)标头字段设置为包含相关图像的页面的 URL 应该可以解决问题,但您可能应该检查 Craigslist 以确保这样做不会违反他们的服务条款。否则,他们很有可能会将您应用的用户代理字符串列入黑名单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 2013-03-12
    相关资源
    最近更新 更多