2011-09-14 164 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()); 
}