44import android .webkit .MimeTypeMap ;
55import android .webkit .URLUtil ;
66
7+ import org .wordpress .android .util .AppLog .T ;
8+
79import java .io .UnsupportedEncodingException ;
810import java .net .IDN ;
911import java .net .URI ;
12+ import java .net .URL ;
1013import java .net .URLDecoder ;
1114import java .net .URLEncoder ;
1215import java .nio .charset .Charset ;
@@ -52,11 +55,40 @@ public static String convertUrlToPunycodeIfNeeded(String url) {
5255 return url ;
5356 }
5457
58+ /**
59+ * Remove leading double slash, and inherit protocol scheme
60+ */
61+ public static String removeLeadingDoubleSlash (String url , String scheme ) {
62+ if (url != null && url .startsWith ("//" )) {
63+ url = url .substring (2 );
64+ if (scheme != null ) {
65+ if (scheme .endsWith ("://" )){
66+ url = scheme + url ;
67+ } else {
68+ AppLog .e (T .UTILS , "Invalid scheme used: " + scheme );
69+ }
70+ }
71+ }
72+ return url ;
73+ }
74+
75+ /**
76+ * Add scheme prefix to an URL. This method must be called on all user entered or server fetched URLs to ensure
77+ * http client will work as expected.
78+ *
79+ * @param url url entered by the user or fetched from a server
80+ * @param isHTTPS true will make the url starts with https;//
81+ * @return transformed url prefixed by its http;// or https;// scheme
82+ */
5583 public static String addUrlSchemeIfNeeded (String url , boolean isHTTPS ) {
5684 if (url == null ) {
5785 return null ;
5886 }
5987
88+ // Remove leading double slash (eg. //example.com), needed for some wporg instances configured to
89+ // switch between http or https
90+ url = removeLeadingDoubleSlash (url , (isHTTPS ? "https" : "http" ) + "://" );
91+
6092 if (!URLUtil .isValidUrl (url )) {
6193 if (!(url .toLowerCase ().startsWith ("http://" )) && !(url .toLowerCase ().startsWith ("https://" ))) {
6294 url = (isHTTPS ? "https" : "http" ) + "://" + url ;
@@ -78,7 +110,8 @@ public static String normalizeUrl(final String urlString) {
78110 // this routine is called from some performance-critical code and creating a URI from a string
79111 // is slow, so skip it when possible - if we know it's not a relative path (and 99.9% of the
80112 // time it won't be for our purposes) then we can normalize it without java.net.URI.normalize()
81- if (urlString .startsWith ("http" ) && !urlString .contains ("build/intermediates/exploded-aar/org.wordpress/graphview/3.1.1" )) {
113+ if (urlString .startsWith ("http" ) &&
114+ !urlString .contains ("build/intermediates/exploded-aar/org.wordpress/graphview/3.1.1" )) {
82115 // return without a trailing slash
83116 if (urlString .endsWith ("/" )) {
84117 return urlString .substring (0 , urlString .length () - 1 );
0 commit comments