php - 如何从 URL 获取字符串

标签 php android html http inputstream

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

我的问题是服务器返回错误。 错误不是 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 这样的结果读入字符串吗?

最佳答案

问题是在出错时,Http header 是 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;

关于php - 如何从 URL 获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418591/

相关文章:

javascript - 如何检查 USERNAME 是否已经存在于 PHP/MYSQL 中?

android - 跨 Android 设备的屏幕灵敏度

javascript - 使用ajax和perl更新html

javascript - 使用 javascript 处理跨浏览器功能

php - 如何将表中的多行更新到MySQL

php - 如何在 Laravel 5.5 中进行迁移?

PHP 和 AJAX 问题?

android - 以编程方式连接到 Android Q 中的 Wifi

java - Android Camera2 - 当 E/Camera 不可用时回调拦截 E/Camera 错误(即用户自拍)

javascript - 不同父页面的不同样式表