stringWithContentsOfURL和HTTP 500错误代码

时间:2022-02-26 05:38:58

I am trying to pull some data from a server (I don't own the server) however it returns some needed data with a http 500 error code, however NSString stringWithContentsOfURL returns nil if the server returns http code 500.

我试图从服务器(我不拥有服务器)中提取一些数据但是它返回一些需要的数据,其中包含http 500错误代码,但是如果服务器返回http代码500,则NSString stringWithContentsOfURL返回nil。

I'd like to retrieve the data even if the server returns 500.

即使服务器返回500,我也想检索数据。

2 个解决方案

#1


NSURLConnection (as part of the URL Loading System) will give you the lower-level control over the request and the interpretation of the response; you will have to implement a few call-back methods to handle fine grained control of the request (and you can opt to invoke it synchronously to mimic stringWithContentsOfURL:, but it will give you what you want.

NSURLConnection(作为URL加载系统的一部分)将为您提供对请求的低级控制和响应的解释;你将不得不实现一些回调方法来处理请求的细粒度控制(你可以选择同步调用它来模仿stringWithContentsOfURL:,但它会给你你想要的。

[NSString stringWithContentsOfURL:] is a great convenience, but in your case you want to circumvent the way cocoa interprets HTTP response codes, so that requires a smidge more work.

[NSString stringWithContentsOfURL:]是一个很好的方便,但在你的情况下你想要绕过cocoa解释HTTP响应代码的方式,所以这需要更多的工作。

#2


You can carefully use this code (never from GUI thread):

您可以仔细使用此代码(从不来自GUI线程):

NSURLRequest * request = ...

NSError * error = nil;
NSURLResponse * response = nil;

NSData * data = [NSURLConnection sendSynchronousRequest:request 
                                      returningResponse:&response 
                                                  error:&error];

NSInteger httpCode = [(NSHTTPURLResponse *)response statusCode];

#1


NSURLConnection (as part of the URL Loading System) will give you the lower-level control over the request and the interpretation of the response; you will have to implement a few call-back methods to handle fine grained control of the request (and you can opt to invoke it synchronously to mimic stringWithContentsOfURL:, but it will give you what you want.

NSURLConnection(作为URL加载系统的一部分)将为您提供对请求的低级控制和响应的解释;你将不得不实现一些回调方法来处理请求的细粒度控制(你可以选择同步调用它来模仿stringWithContentsOfURL:,但它会给你你想要的。

[NSString stringWithContentsOfURL:] is a great convenience, but in your case you want to circumvent the way cocoa interprets HTTP response codes, so that requires a smidge more work.

[NSString stringWithContentsOfURL:]是一个很好的方便,但在你的情况下你想要绕过cocoa解释HTTP响应代码的方式,所以这需要更多的工作。

#2


You can carefully use this code (never from GUI thread):

您可以仔细使用此代码(从不来自GUI线程):

NSURLRequest * request = ...

NSError * error = nil;
NSURLResponse * response = nil;

NSData * data = [NSURLConnection sendSynchronousRequest:request 
                                      returningResponse:&response 
                                                  error:&error];

NSInteger httpCode = [(NSHTTPURLResponse *)response statusCode];