@@ -485,6 +485,7 @@ internal class _HTTPURLProtocol: _NativeProtocol {
485
485
case . noDelegate, . dataCompletionHandler, . downloadCompletionHandler:
486
486
// Follow the redirect. Need to configure new request with cookies, etc.
487
487
let configuredRequest = session. _configuration. configure ( request: request)
488
+ task? . knownBody = URLSessionTask . _Body. none
488
489
startNewTransfer ( with: configuredRequest)
489
490
}
490
491
}
@@ -597,6 +598,7 @@ extension _HTTPURLProtocol {
597
598
// Otherwise, we'll start a new transfer with the passed in request.
598
599
if let r = request {
599
600
lastRedirectBody = nil
601
+ task? . knownBody = URLSessionTask . _Body. none
600
602
startNewTransfer ( with: r)
601
603
} else {
602
604
// If the redirect is not followed, return the redirect itself as the response
@@ -649,38 +651,31 @@ internal extension _HTTPURLProtocol {
649
651
/// - SeeAlso: <https://tools.ietf.org/html/rfc7231#section-6.4>
650
652
func redirectRequest( for response: HTTPURLResponse , fromRequest: URLRequest ) -> URLRequest ? {
651
653
//TODO: Do we ever want to redirect for HEAD requests?
652
- func methodAndURL( ) -> ( String , URL ) ? {
653
- guard
654
- let location = response. value ( forHeaderField: . location) ,
655
- let targetURL = URL ( string: location)
656
- else {
657
- // Can't redirect when there's no location to redirect to.
658
- return nil
659
- }
660
-
661
- let method = fromRequest. httpMethod ?? " GET "
662
- // Check for a redirect:
663
- switch response. statusCode {
664
- case 301 , 302 :
665
- // Change "POST" into "GET" but leave other methods unchanged:
666
- let newMethod = ( method == " POST " ) ? " GET " : method
667
- return ( newMethod, targetURL)
668
-
669
- case 303 :
670
- return ( " GET " , targetURL)
671
-
672
- case 305 ... 308 :
673
- // Re-use existing method:
674
- return ( method, targetURL)
675
-
676
- default :
677
- return nil
678
- }
654
+
655
+ guard
656
+ let location = response. value ( forHeaderField: . location) ,
657
+ let targetURL = URL ( string: location)
658
+ else {
659
+ // Can't redirect when there's no location to redirect to.
660
+ return nil
679
661
}
680
-
681
- guard let ( method, targetURL) = methodAndURL ( ) else { return nil }
662
+
682
663
var request = fromRequest
683
- request. httpMethod = method
664
+
665
+ // Check for a redirect:
666
+ switch response. statusCode {
667
+ case 301 ... 302 where request. httpMethod == " POST " , 303 :
668
+ // Change "POST" into "GET" but leave other methods unchanged:
669
+ request. httpMethod = " GET "
670
+ request. httpBody = nil
671
+
672
+ case 301 ... 302 , 305 ... 308 :
673
+ // Re-use existing method:
674
+ break
675
+
676
+ default :
677
+ return nil
678
+ }
684
679
685
680
// If targetURL has only relative path of url, create a new valid url with relative path
686
681
// Otherwise, return request with targetURL ie.url from location field
0 commit comments