使用HTTP URLConnection发布到服务器时发生java.io.EoFException

时间:2013-02-25 13:28:02

标签: android http-post

使用HTTP URLCOnnection发布到服务器时发生

java.io.EoFException 。它是随机发生的。为什么会发生这种错误。我关闭了outStream并刷了它。但是没有用。

我的代码:

// Post request on server
public static String post(String serverUrl, Map<String, String> params) throws IOException {

InputStream is = null;
OutputStream out = null;

int len = 1000;// Only display the first 500 characters of the retrieved web page content.

try {
    url = new URL(serverUrl);
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

StringBuilder bodyBuilder = new StringBuilder();

iterator = params.entrySet().iterator();

while (iterator.hasNext()) {
    Entry<String, String> param = iterator.next();
    bodyBuilder.append(param.getKey()).append("=")
            .append(param.getValue());

    if (iterator.hasNext()) {
        bodyBuilder.append("&");
    }
}

String body = bodyBuilder.toString();

byte[] bytes = body.getBytes();

String responseMessage ="";
HttpURLConnection conn = null;
String responseAsString ="";
try {
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");

    out = conn.getOutputStream();
    out.write(bytes);
    out.flush();

    int responseCode = conn.getResponseCode();

    responseMessage = conn.getResponseMessage();

    if (responseCode==200) {
           is = conn.getInputStream();
            // Convert the InputStream into a string
           responseAsString = readIt(is, len);
           responseAsString=responseAsString.trim();
    }
    else
    {
        throw new IOException("post failed with error "
                + conn.getResponseMessage());
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (conn != null) {
        conn.disconnect();
    }
    if (is != null) {
        is.close();
    } 
    if (out != null) {
        out.close();
    } 
}
return responseAsString;
}

public static String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");        
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}

0 个答案:

没有答案