summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/service/download/APRedirectHandler.java
blob: ddf8d605ddce708f7df345b72176d951377930c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package de.danoeh.antennapod.service.download;

import android.util.Log;
import de.danoeh.antennapod.BuildConfig;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.protocol.HttpContext;

import java.net.URI;

public class APRedirectHandler extends DefaultRedirectHandler {
	// Identifier for logger
	private static final String TAG = "APRedirectHandler";
	// Header field, which has to be potentially fixed
	private static final String LOC = "Location";
	// Regular expressions for character strings, which should not appear in URLs
	private static final String CHi[] = { "\\{", "\\}", "\\|", "\\\\", "\\^", "~",   "\\[", "\\]", "\\`"};
	private static final String CHo[] = { "%7B", "%7D", "%7C", "%5C",  "%5E", "%7E", "%5B", "%5D", "%60"};

	/**
	 * Workaround for broken URLs in redirection.
	 * Proper solution involves LaxRedirectStrategy() which is not available in
	 * current API yet.
	 */
	@Override
	public URI getLocationURI(HttpResponse response, HttpContext context)
			throws org.apache.http.ProtocolException {

		Header h[] = response.getHeaders(LOC);
		if (h.length>0) {
			String s = h[0].getValue();

			// Fix broken URL
			for(int i=0; i<CHi.length;i++)
				s = s.replaceAll(CHi[i], CHo[i]);

			// If anything had to be fixed, then replace the header
			if (!s.equals(h[0].getValue()))
			{
				if (BuildConfig.DEBUG)
					Log.d(TAG, "Original URL: " + h[0].getValue());
				
				response.setHeader(LOC, s);

				if (BuildConfig.DEBUG)
					Log.d(TAG, "Fixed URL:    " + s);
			}
		}

		// call DefaultRedirectHandler with fixed URL
		return super.getLocationURI(response, context);
	}
}