2011-09-14 163 views
2

我的應用程序從php web服務器獲取大部分數據。如何從URL中獲取字符串

我的問題是當服務器返回錯誤。 錯誤不是HTML頁面,而是簡單的字符串。 例如:

ERROR001 

可能代表無效名稱。

這裏是我的代碼:

String responseBody = null; 
URL url = new URL(strUrl); 
URLConnection connection; 
connection = url.openConnection(); 
connection.setUseCaches(false); 
InputStream isResponse = (InputStream) connection.getContent(); // on errors I get IOException here 
responseBody = convertStreamToString (isResponse); 

當我使用它,我得到IOException異常上connection.getContent();

我也試過:

HttpGet getMethod = new HttpGet(url); 
String responseBody = null; 
responseBody = mClient.execute(getMethod,mResponseHandler); // on errors I getClientProtocolException 

,但我得到getClientProtocolException上mClient.execute

任何想法如何,我可以讀出ERROR001入一個字符串的結果?

+0

我用PHP相當陌生,但你檢查從服務器回來的resposne代碼?通常,這是判斷您是否收到有效回覆的可靠方法。 – Brandon

+0

這實際上與PHP沒有任何關係。有一個異常被拋出,而不是在客戶端處理。 try/catch是需要的,而不是嘗試解釋錯誤的響應主體。 –

+0

我剛剛注意到,當網頁的響應是「OK」時,我沒有錯誤。只有當結果的格式爲「ERRORXXX」 –

回答

1

的問題是,在錯誤的HTTP標頭是HTTP錯誤500(內部服務器錯誤)。 讀書,我用下面的代碼錯誤內容:

String responseBody = null; 
    URL url = new URL(strUrl); 
    HttpURLConnection connection; 
    connection = (HttpURLConnection) url.openConnection(); 
    connection.setUseCaches(false); 
    InputStream isResponse = null; 
    try { 
     isResponse = connection.getInputStream(); 
    } catch (IOException e) { 
     isResponse = connection.getErrorStream(); 
    } 
    responseBody = convertStreamToString (isResponse); 

    return responseBody; 
0
url = new URL(desiredUrl); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setRequestMethod("GET"); 
connection.connect(); 
reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

試試這個。 我想你不是在調用connection.connect()方法。

0

當你使用HttpClien時會發生什麼? 你可能想試試這個:

String responseBody; 

HttpGet request = new HttpGet("your url"); 
HttpClient client = new DefaultHttpClient(); 
HttpResponse httpResponse = client.execute(request); 
HttpEntity entity = httpResponse.getEntity(); 

if(entity != null){ 
    responseBody = convertStreamToString (entity.getContent()); 
}