【问题标题】:Getting Null response while hitting https URL在点击 https URL 时获得空响应
【发布时间】:2016-06-14 05:18:52
【问题描述】:

在目标 C 中点击 https url 时遇到一些问题。这是我的代码。

- (void)viewDidLoad {

   NSString *urlString = [NSString stringWithFormat:@"MY URL",uid];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
                                    [NSURL URLWithString:urlString]];
    [request setHTTPShouldHandleCookies:YES];
    [request setHTTPMethod:@"GET"];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    NSUInteger responseStatusCode = [httpResponse statusCode];
    _responseData = [[NSMutableData alloc] init];
    [self.responseData setLength:0];

    NSLog(@"connection");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
    NSLog(@"_responseData%@",_responseData);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSError *jError;
   NSArray *myApps= [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingAllowFragments error:&jError];
    NSLog(@"jError:%@",jError);
}

当我在模拟器中运行应用程序时,有时会获得 myApps 值。 但是大部分时间都没有得到响应。那时我能够看到 _responseDatamyApps 的值为空。像这样获取 responseData

_responseData

像 this.myApps 这样的错误是空的

jError:Error Domain=NSCocoaErrorDomain Code=3840 "周围的值无效 字符 0。” UserInfo={NSDebugDescription=无效值 字符 0.}

当我收到此错误时,我尝试在浏览器中点击 URL,却在浏览器中得到响应。 所以我再次清理并运行应用程序,仍然面临同样的问题。 但是,如果更改模拟器,例如在 iPhone 6s 中运行并出现错误,现在更改为 iPhone 6,而不是得到响应。

谁能帮帮我。

【问题讨论】:

  • connectionDidFinishLoading: 中,将_responseData 转换为NSString,看看你有什么。
  • 我试过 NSString* newStr = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding]; .但是我得到了 标签格式的响应,例如

标签: ios objective-c json nsurlconnection


【解决方案1】:

当您尝试以不正确的方式处理 cookie 时会发生这种情况。从您的代码中删除以下行并检查。

[request setHTTPShouldHandleCookies:YES];

【讨论】:

  • 我试过这个并在同一个模拟器中运行,但仍然得到空响应:(
【解决方案2】:

有时,撇号 (')、空格或某些特殊字符可能会导致 NSMutableURLRequest 返回“空”URL。 在将字符串 url 传递给 NSMutableURLRequest 之前对其进行编码(百分比转义编码),如下所示:

NSString *updatedPhotoUrl     = originalUrlString ;

updatedPhotoUrl               = [updatedPhotoUrl stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];

NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: updatedPhotoUrl]];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2019-11-18
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多