Php 如何从URL获取字符串

Php 如何从URL获取字符串,php,android,html,http,inputstream,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); InputStr

我的应用程序从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这样的结果读入字符串

url = new URL(desiredUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
试试这个。
我认为您没有调用connection.connect()方法。

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

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

我对PHP相当不熟悉,但是您是否检查了从服务器返回的resposne代码?通常,这是判断您是否收到有效响应的可靠方法。这实际上与PHP无关。有一个异常正在抛出,而不是在客户端处理。需要try/catch,而不是试图解释错误的响应主体。我只是注意到,当来自web页面的响应为“OK”时,我没有得到错误。只有当结果为“ERRORXXX”时,才会发生异常。我同意Paul Sasik-添加try/catch块,并在该块中尝试读取您的响应。当我在我的PC浏览器上尝试URL时,我得到“ERRORXXX”,这正是我希望在应用程序中得到的结果。相反,我得到了一个例外。我想在客户端(我的端)检查它,但是在我可以阅读它之前我得到了异常。