簡體   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