发送JSON请求时,getInputStream会抛出EOFException

时间:2013-10-09 02:51:10

标签: java android json request eofexception

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

造成此例外的原因是什么?

1 个答案:

答案 0 :(得分:0)

public class EOFException扩展IOException:

表示在输入过程中意外地达到了文件结尾或流结束。

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

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