2012-09-20 69 views
0

我試圖訪問特定的網址URL重定向錯誤,如果URL中包含保留字符

DefaultHttpClient httpclient = new DefaultHttpClient(); 
httpclient.getCredentialsProvider().setCredentials(new AuthScope("abc.com", 443), 
       new UsernamePasswordCredentials("user", "Passwd")); 

HTTPHelper http = new HTTPHelper(httpclient); 

http.get("http://abc.com/**aaa**/w/api.php?param=timestamp%7Cuser&format=xml"); 

其中%7C = |

被重定向我到以下網址內部

http://abc.com/**bbb**/w/api.php?param=timestamp%257Cuser&format=xml 

正因爲如此,我不能夠得到正確的輸出...

| ==>%7C 

%==> %25 

%7C == %257C 

我想查詢被timestamp|user 但由於循環重定向,它被改爲timestamp%7Cuser 有什麼辦法可以避免這種情況?

我寫我自己的自定義重定向策略也

httpclient.setRedirectStrategy(new DefaultRedirectStrategy() { 
      public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) { 
       boolean isRedirect = false; 
       try { 
        isRedirect = super.isRedirected(request, response, context); 
        LOG.info(response.getStatusLine().getStatusCode()); 
        LOG.info(request.getRequestLine().getUri().replaceAll("%25", "%")); 
       } catch (ProtocolException e) { 
        e.printStackTrace(); 
       } 
       if (!isRedirect) { 
        int responseCode = response.getStatusLine().getStatusCode(); 
        if (responseCode == 301 || responseCode == 302) { 
         return true; 
        } 
       } 
       return isRedirect; 
      } 
     }); 

但我不知道如何與%7C從重定向的URL代替%25℃

回答

0

不只是http.get("http://abc.com/**aaa**/w/api.php?param=timestamp|user&format=xml"); 工作?

你的意思是「將我重定向到內部的以下URL」?這就像你的網址再次編碼。你可以在HTTPHelper中發佈代碼嗎?我的下面的測試代碼正常工作。

客戶端代碼:

HttpClient client = new DefaultHttpClient(); 
HttpGet get = new HttpGet("http://localhost:8080/test/myservlet?param=timestamp%7Cuser&format=xml"); 
client.execute(get); 

servlet代碼:

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

     String param = request.getParameter("param"); //get timestamp|user 
     String format = request.getParameter("format"); 

    } 
+0

沒有。它拋出IllegalArgumentException – sparkle

+0

我刷新了我的答案 – secondflying

+0

主機「abc.com/**aaa**」被永久移動到其他服務器。我收到301響應,然後重定向到「abc.com/**bbb**」。在重定向時,url再次被編碼。我試圖攔截重定向,並在中間再次進行網址解碼。但無法這樣做.. – sparkle

1

它看起來像網站的URL重寫規則只是打破。如果不是您的網站,您可能需要聯繫維護人員並告知他們有關問題。

與此同時,是否有一些原因,您爲什麼不能直接簡單地使用目標URL(即http://abc.com/**bbb**/w/api.php?...),避免重定向?

+0

感謝IImari的迴應...但我沒有控制該網站..我建立網址從信息來自網站,這是給我的網址http:// abc .com/** aaa **/....我可以通過編寫我自己的自定義重定向處理程序來做些什麼嗎? – sparkle

+0

你可以嘗試一下,但說實話,你只是寫了一個方法來解決特定網站被破壞的特定方式。您的自定義處理程序對其他任何網站都不太有用(甚至可能會破壞其中的一些網站),但如果破損的網站更改其重寫規則,則無法保證它可以繼續工作。所以,既然你會實施特定於網站的黑客攻擊,爲什麼不加一些代碼,以便當網站告訴你使用'abc.com/** aaa **'時,用'abc替換它.COM/** ** BBB'? –

相關問題