gpt4 book ai didi

iOS HTTP 后重定向处理程序不工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:21:54 25 4
gpt4 key购买 nike

我是 iOS 开发新手。我只是想向服务器发出 post 请求,但遇到了提到的问题 here与服务器重定向。我使用了答案中提到的事件处理程序,但仍然无法正常工作。

这是我的 .m 代码:​​

@interface ViewController ()

@end

@implementation ViewController


#pragma mark NSURLConnection Delegate Methods


//CALL BACK METHODS

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@" didReceiveResponse");
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it


//initialize response
_responseData = [[NSMutableData alloc] init];

}

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



}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}




- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@" connectionDidFinishLoading ");

// The request is complete and data has been received
// You can parse the stuff in your instance variable now

NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(@" async response data: %@", dataReceived);



}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@" didFailWithError");

// The request has failed for some reason!
// Check the error var
}



- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.


NSString *post = [NSString stringWithFormat:@"&j_username=%@&j_password=%@",@"usrname",@"pw"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

request = [[NSMutableURLRequest alloc] init];
request.HTTPMethod= @"POST";
//parameters
[request setURL:[NSURL URLWithString:@"url"]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
[request setHTTPBody:postData];




// Send a synchronous request
if (0) {
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSLog(@" Synchronous request done");
if (error == nil)
{
// Parse data here
NSLog(@" Synchronous response has no error");
NSLog(@" Synchronous Reply: %@", response);
}
}
else {
// Send Asynchronous request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection connectionWithRequest:request delegate:self];
NSLog(@" Asynchronous request sent");
}



}

- (NSURLRequest *)connection: (NSURLConnection *)connection
willSendRequest: (NSURLRequest *)inRequest
redirectResponse: (NSURLResponse *)redirectResponse;
{
if (redirectResponse) {
// we don't use the new request built for us, except for the URL
NSURL *newURL = [request URL];
NSString *redirectURL= [newURL absoluteString];
NSLog(@"Redirect URL: ");
NSLog(redirectURL);
// Previously, store the original request in _originalRequest.
// We rely on that here!
NSMutableURLRequest *newRequest = [request mutableCopy];
[newRequest setURL: newURL];
NSLog(@"redirect occur");
return newRequest;
} else {
NSLog(@"no redirect");
return inRequest;
}
}

@end

没有处理程序,请求可以正常进行(只是没有附加主体);但是使用处理程序,重定向会一次又一次地被检测到 b/c 重定向的 url 与原始 url 相同。最终,由于重定向过多,请求死亡。我认为这可能是服务器端问题,但我在导致此问题的编码中做错了什么吗?

最佳答案

基本上问题是 redirectResponse 的 url 不是你被重定向到的地方;它仍然是您在原始发布方法中设置的那个。这就是您一次又一次被重定向到同一个 URL 的原因。

所以你想做的是拦截你在响应头中被重定向到的实际 url。执行初始发布请求后,您应该得到如下响应 header :

HTTP/1.1 302 Found
Location: http://www.iana.org/domains/example/

其中“位置”表示您将被重定向到的位置。所以像这样获取 url:

NSDictionary* headers = [(NSHTTPURLResponse *)redirectResponse allHeaderFields];
NSString newUrl=headers[@"Location"];

在你的 newRequest 中使用 newUrl,然后你就可以开始了。

关于iOS HTTP 后重定向处理程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com