2012-09-14 19 views
0

我需要在我的Web應用程序中加載外部URL的內容。嘗試使用java中的相對URL來收取外部URL的內容

我試過用HttpsUrlConnection和HttpCliente,我忘了它,但我有相對URL的問題,因爲它沒有工作。

如果我的web應用程序是http://example1.com我嘗試收取http://external.com含量,http://external.com/images/g.jpg例如相對URL,試圖在http://example1.com/images/g.jpg解決。

我很絕望,我尋找谷歌,但我什麼也找不到。

我很抱歉我的英語不好。

謝謝!!! :-)

PD:有我的代碼(代碼是太陽神說,大約爲絕對URL變化相對URL,但它doesn't工作...)

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); 
     } 

    } 
+0

你可以在示例代碼中添加示例代碼,以瞭解你在嘗試什麼? – fglez

+0

我編輯我的問題添加代碼,謝謝! –

+0

向上使用格式化按鈕。代碼按鈕在文字前放置4個空格。這意味着一個代碼塊。 – helios

回答

0

你想要做的與Apache的mod_rewrite module類似。

它基本上必須重寫提供的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總是前面有一個雙引號"這樣的前綴可能包括開始" 。當然......可能會有錯誤的地方......

+0

而你的英語並不差。至少爲了寫這個問題:) – helios

+0

感謝您的回答Helios! 我試過了(更改網址),但它仍然沒有工作,當我看到源代碼時,網址沒問題,但它並沒有工作,我想也許我必須改變一些標題前發送請求,我嘗試尋找這個,但我找不到任何東西! P.D:謝謝你的英文:-) –

+0

當你(作爲一個瀏覽器客戶端)收到這個頁面......寫得很好嗎?我的意思是:它是否包含 ...? – helios