如何故意创建非标准或格式错误的Java URL对象

时间:2016-01-10 21:21:37

标签: java android url android-glide

我正在尝试使用Glide Android库从网址加载图片,例如

String urlString = "https://images.example.com/is/image/example/EXMPL1234_021347_1?$cdp_thumb$";

当我将上面的url字符串输入Glide时,

Glide.with(mContext).load(urlString).into(view);

它实际点击的地址是:

https://images.example.com/is/image/example/EXMPL1234_021347_1?%24cdp_thumb%24

对我来说不对。必须保留$。

然后我尝试传入java.net.URL对象,但我似乎无法构造一个在查询中保留$字符的对象。

这是我尝试过的一个例子:

    URL url = null;
    try
    {
        url = new URL(urlStr);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath()+"?$hp_wn_thumb_app$", "", url
                .getRef()
                +"?$hp_wn_thumb_app$");
        url = uri.toURL();
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (URISyntaxException e)
    {
        e.printStackTrace();
    }

如果有人能提出解决方案,我将非常感激。制作非urlencoded的java URL对象。

1 个答案:

答案 0 :(得分:0)

这解决了这个原始问题。

package com.techventus;

import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.Headers;

import java.net.MalformedURLException;
import java.net.URL;

/*
// Necessary to help make correct calls to the API which does not apply and //URL special Character correction.
*/
public class CorrectGlideUrl extends GlideUrl
{
    String urlString;

    public CorrectGlideUrl(URL url)
    {
        super(url);
    }

    public CorrectGlideUrl(String url)
    {
        super(url);
        urlString = url;
    }

    public CorrectGlideUrl(URL url, Headers headers)
    {
        super(url, headers);
    }

    public CorrectGlideUrl(String url, Headers headers)
    {
        super(url, headers);
    }

    /**
     *
     * Returns a properly escaped {@link String} url that can be used to make http/https requests.
     *
     * @see #toURL()
     * @see #getCacheKey()
     */
    @Override
    public String toStringUrl() {

        return urlString.replace("%24","$");
//      return getSafeStringUrl();
    }


    /**
     * Returns a properly escaped {@link java.net.URL} that can be used to make http/https requests.
     *
     * @see #toStringUrl()
     * @see #getCacheKey()
     * @throws MalformedURLException
     */
    @Override
    public URL toURL() throws MalformedURLException {
        return getSafeUrl();
    }

    // See http://stackoverflow.com/questions/3286067/url-encoding-in-android. Although the answer using URI would work,
    // using it would require both decoding and encoding each string which is more complicated, slower and generates
    // more objects than the solution below. See also issue #133.
    private URL getSafeUrl() throws MalformedURLException {

        return null;
    }


}