【发布时间】:2014-05-24 09:36:01
【问题描述】:
我正在使用此代码从使用 AsyncTask 的 URL 获取数据:
protected String doInBackground(Object... params) {
int ResponseCode=-1;
try {
URL myURL=new URL("URL...");
HttpURLConnection connection=(HttpURLConnection) myURL.openConnection();
connection.connect();
ResponseCode=connection.getResponseCode();
if (ResponseCode==HttpURLConnection.HTTP_OK) {
InputStream inputStream=connection.getInputStream();
Reader reader=new InputStreamReader(inputStream);
int contentLength=connection.getContentLength();
char[] charArray=new char[contentLength];
reader.read(charArray);
String responseData=new String(charArray);
Log.i("TAG", responseData);
Log.i("TAG", ""+contentLength);
}
else {
Log.i("TAG", " Unsuccessful HTTP Response Code: "+ResponseCode);
}
}catch (MalformedURLException e) {
Log.i("TAG", "MalformedURLException Error: "+e.getMessage());
} catch (IOException e) {
Log.i("TAG", "IOException Error: "+e.getMessage());
} catch (Exception e) {
Log.i("TAG", "Exception Error: "+e);
}
return " "+ResponseCode;
}
上面的代码工作正常,我在一些项目中使用它,但是对于我正在处理的 URL,它不起作用并且总是为 Response Code,because the HTTP response of my URL doesn't contain Content-Length header, the content is chunked. 返回 -1,现在我想知道有没有有什么等效的方法吗?
在此致谢
【问题讨论】:
-
"...有没有等效的方法可以做到这一点?":很简单,没有。除非您下载整个内容并在之后检查长度,否则没有办法。唯一的可能性是,如果您控制服务器端代码并添加
Content-Length响应或其他查询长度的方式。 -
谢谢,但服务器不在我的控制范围内。
标签: java android httpconnection