0

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

是什么导致了这个异常?

4

1 回答 1

0

公共类 EOFException 扩展了 IOException:

表示输入期间意外到达文件结尾或流结尾。

http://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html

您正在呼叫conn.getOutputStream();,然后呼叫conn.getInputStream();而不重置。您已经在文件的末尾。

于 2013-10-09T03:06:38.570 回答