简体   繁体   English

如何从URL获取字符串

[英]How can I get a String from a URL

My application gets most of its data from a php web server. 我的应用程序从php Web服务器获取大部分数据。

My problem is when the server return errors. 我的问题是服务器返回错误时。 The errors are not HTML pages, but simple strings. 错误不是HTML页面,而是简单的字符串。 for example: 例如:

ERROR001

could stand for invalid name. 可能代表无效名称。

here is my code: 这是我的代码:

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

When I use it, I get IOException on connection.getContent(); 使用它时,我在connection.getContent()上得到IOException。

I also tried: 我也尝试过:

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

but I get getClientProtocolException on mClient.execute 但是我在mClient.execute上得到了getClientProtocolException

Any ideas how I could read a result like ERROR001 into a string? 有什么想法可以将类似ERROR001的结果读入字符串吗?

The problem is that on error, the Http header is HTTP Error 500 (Internal server error). 问题是出现错误时,Http标头为HTTP错误500(内部服务器错误)。 To read the error content I used the following code: 要读取错误内容,我使用了以下代码:

    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;
url = new URL(desiredUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

Try this one. 试试这个。 I think you are not calling the connection.connect() method. 我认为您没有在调用connection.connect()方法。

What happens when you use HttpClien? 使用HttpClien会发生什么? you may want to try this: 您可能想尝试一下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM