如何从 URL 获取字符串
我的应用程序从 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 这样的结果读取到字符串中吗?
My application gets most of its data from a php web server.
My problem is when the server return errors.
The errors are not HTML pages, but simple strings.
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();
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
Any ideas how I could read a result like ERROR001 into a string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是,出现错误时,Http 标头为 HTTP 错误 500(内部服务器错误)。
为了读取错误内容,我使用了以下代码:
The problem is that on error, the Http header is HTTP Error 500 (Internal server error).
To read the error content I used the following code:
试试这个。
我认为你没有调用connection.connect()方法。
Try this one.
I think you are not calling the connection.connect() method.
使用 HttpClient 时会发生什么?
你可能想尝试这个:
What happens when you use HttpClien?
you may want to try this: