2011-09-14 15 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); 

私はそれを使用すると、私は)connection.getContentにIOExceptionが(取得します。

私も試してみました:

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

を私は、私は文字列にERROR001のような結果を読むことができる方法mClient.execute

上の任意のアイデアをgetClientProtocolExceptionを取得しますか?

+0

を私はPHPとかなり慣れていないんだけど、あなたは、サーバーから戻ってくるresposneコードをチェックしていますか?一般的に、それはあなたが有効な応答を受け取ったかどうかを確認する信頼できる方法です。 – Brandon

+0

これは実際にはPHPとは関係ありません。スローされ、クライアント側で処理されない例外があります。悪いレスポンスボディを解釈しようとするのではなく、try/catchが必要です。 –

+0

私は、Webページからの応答が「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()); 
} 
関連する問題