我在以下 Android 代码中从 getInputStream 获得一个 EOFException。
private void downloadUrl() {
HttpsURLConnection conn = null;
DataOutputStream printout = null;
try {
try {
conn = (HttpsURLConnection) new URL("some url").openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
}
catch (ProtocolException e){
}
JSONObject jsonReq = new JSONObject();
jsonReq.put("userID", "id");
jsonReq.put("password", "1234");
OutputStream output = conn.getOutputStream();
try {
OutputStreamWriter wr = new OutputStreamWriter(output);
wr.write(URLEncoder.encode(jsonReq.toString(),"utf-8"));
wr.flush();
wr.close();
}
catch (IOException e) {
}
InputStream in = conn.getInputStream(); //I get EOFException here
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String responseSingle = null;
while ((responseSingle = rd.readLine()) != null) {
response = response + responseSingle;
}
rd.close();
}
catch (IOException e) {
}
finally {
if (in != null)
in.close();
}
}
catch (IOException e){
}
catch (JSONException e) {
}
finally{
if(conn!=null)
conn.disconnect();
}
}
是什么导致了此异常?
公共类EOFException扩展了IOException:
表示在输入期间意外到达文件末尾或流末尾。
http://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html
您正在调用conn.getOutputStream();
,然后在不重置的情况下调用conn.getInputStream();
。 您已经在文件的末尾。