繁体   English   中英

尝试使用Java中的相对URL收费外部URL的内容

[英]trying to charge content of a external url with relative url in java

我需要在Web应用程序中加载外部URL的内容。

我用HttpsUrlConnection和HttpCliente尝试过,我忘记了,但是相对URL出现问题,因为它不起作用。

如果我的web应用程序是http://example1.com ,我试图充电的内容http://external.com ,相对URL http://external.com/images/g.jpg例如,试图在http://example1.com/images/g.jpg解决。

我很拼命,我正在寻找谷歌,但我什么也没找到。

对不起,我的英语不好。

谢谢!!! :-)

PD:有我的代码(代码中helios谈到了将绝对URL更改为相对URL,但这是行不通的...)

codigoHtml具有带有相对链接的html代码,它不起作用!

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {      

        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.getParams().setParameter(ClientPNames.DEFAULT_HOST, new HttpHost("host_to_redirect"));       

        HttpPost httpPost = new HttpPost("host_to_redirect/action.do");

        httpPost.addHeader("Location", "host_to_redirect");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("name", "value"));
        nameValuePairs.add(new BasicNameValuePair("name", "value"));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = httpclient.execute(httpPost);

        httpResponse.addHeader("Location", "host_to_redirect");

        HttpEntity entity = httpResponse.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(httpResponse.getStatusLine());
        System.out.println("----------------------------------------");

        if (entity != null) {
            // System.out.println(EntityUtils.toString(entity));
            response.setHeader("Location", "https://prepliberty.tirea.es:8065/pliberty");
            response.addHeader("Location", "https://prepliberty.tirea.es:8065/pliberty");

            String codigoHtml = EntityUtils.toString(entity);

            codigoHtml = codigoHtml.replaceAll("plib_script/", "host_to_redirect/plib_script/");            
            codigoHtml = codigoHtml.replaceAll("plib_css/", "host_to_redirect/plib_css/");
            codigoHtml = codigoHtml.replaceAll("plib_images/", "host_to_redirect/plib_images/");

            response.getWriter().write(codigoHtml);
        }   

    }

您尝试做的事情类似于Apache的mod_rewrite模块所做的事情。

它基本上必须重写提供的URL。 没有魔术子弹。 因此,如果内容不是很复杂,我应该建议您将内容作为字符串获取,并进行替换(或多次替换)。

就像是:

String html = ...content from URL... //beware of encoding!!! a lot of programmers neglect this!
html = html.replace(OLD_PREFIX, NEW_PREFIX);
// now you can use html

OLD_PREFIX可以为http://external.com/而NEW_PREFIX可以为http://example1.com/

您可以考虑到URL总是以双引号"开头,因此前缀可以包括以”开头" 当然...可能有错放的地方...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM