如何从URL获取字符串

时间:2011-09-14 15:05:10

标签: php android html http inputstream

我的应用程序从php Web服务器获取大部分数据。

我的问题是服务器返回错误。 错误不是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

但是我在mClient.execute上得到了getClientProtocolException

如何将ERROR001等结果读入字符串?

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

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

试试这个。 我认为你没有调用connection.connect()方法。

答案 2 :(得分:0)

使用HttpClient时会发生什么? 你可能想试试这个:

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());
}