2014-08-29 62 views
1

考慮我是一個使用HTML和Java的新手。如果您能夠查看我的問題並提供任何建議,我將不勝感激。我基本上嘗試按順序執行以下操作:HTML結果得到編碼

1)使用PostMethod類,通過POST方法在Java中發送HTTP請求。

2)取結果。我接收的結果是HTML格式

3)的實際結果包含像", ;, :等所有的報價是在結果轉換爲實體(& QUOT)(htmlOutput字符串)

我的問題是字符下列。如何避免獲取編碼結果。有沒有一種很好的方式來獲得結果作爲原始字符串,不包含實體(& quot)?以下是我使用的代碼。

 int statusCode = HttpStatus.SC_OK; 
     String scriptOutput = ""; 
     PostMethod runnerMethod = new PostMethod(url); 
     try { 
      runnerMethod.setRequestHeader("X-Forwarded-For", LOCAL_MACHINE_IP); 
      runnerMethod.addParameter("script", serializedScript);  
      statusCode = client.executeMethod(runnerMethod); 
      if (statusCode != HttpStatus.SC_OK) { 
       scriptOutput = "HTTP Post request failed with statusCode" + statusCode + 
           runnerMethod.getStatusText(); 
       throw new Exception(scriptOutput); 
      } 
      String htmlOutput = runnerMethod.getResponseBodyAsString(); 
      scriptOutput = StringUtils.substring(htmlOutput, StringUtils.indexOf(htmlOutput,"Script:") + 8, StringUtils.indexOf(htmlOutput, "<BR/>"));    

      return scriptOutput; 
     } catch (IllegalArgumentException e) { 
      String errMsg = String.format("Error during Background script execution on instance. opId = %s, instanceUrl = %s, HTTP Status Code = %d, Err Message = %s", 
              opId, instanceUrl, statusCode, e.getMessage());   
      return errMsg;    
     } 
     catch (Exception e) 
     { 
      String errMsg = String.format("Error during Background script execution on instance. opId = %s, instanceUrl = %s, HTTP Status Code = %d, Err Message = %s", 
              opId, instanceUrl, statusCode, e.getMessage());    
return errMsg; 
     } 
     finally { 
      runnerMethod.releaseConnection(); 
     } 

輸出樣本如下:

enter image description here

+0

你應該解釋一下你在「點」3)中的「轉換」是什麼意思你確定在'htmlOutput'變量中沒有HTML實體(" s等)? – pwes 2014-08-29 07:03:29

+0

@pwes:我根據你的建議澄清了一點。爲了回答你的問題,htmlOutput確實包含HTML實體,在這種情況下,「而不是實際的」,讓我知道如果我的問題是清楚的 – animageofmine 2014-08-29 07:12:00

回答

1

你要做的就是張貼到HTTP服務器是什麼。我認爲你正在使用Apache Commons HTTPClient。 getResponseBodyAsString()方法中沒有任何內容會將引號轉義爲HTML實體。

可能您嘗試在服務器端發送一個雙JSON編碼的對象(因此它首先編碼爲通常的表示形式,然後是JSON字符串,這將解釋實體)。

正確的解決方案是擺脫雙重編碼。如果您不控制服務器端,則可以使用.replaceAll("&quot;", "\"")或使用Apache Commons StringEscapeUtils as explained elsewhere on StackOverflow

+0

是的結果服務器返回的是JSON字符串,而我正在使用Apache Commons HttpClient。當從服務器返回結果時擺脫雙重編碼?順便說一句,我確實想過使用全部替換,但是那隻能解決一個問題,我不知道我應該替換的其他字符是什麼,我正在開發一個通用客戶端所以結果可能包含其他字符,這些字符可能會改變爲HTML實體。建議? – animageofmine 2014-08-29 07:18:01

+0

正如我上面所寫,StringEscapeUtils(它是apache commons-lang的一部分)可以忽略所有的HTML實體 我不知道是什麼在服務器上完成,所以我不能建議如何擺脫雙編碼沒有更多的信息。 – llogiq 2014-08-29 07:41:29

+0

謝謝。在服務器端,作爲cript(javascript)被執行,結果字符串使用JSON編碼器編碼爲JSON:https://github.com/douglascrockford/JSON-js。例如:[{「key1」:{「subkey1」:「value1」}},{「key2」:{「subkey2」:「value2」}}] – animageofmine 2014-08-29 07:55:04