Android- Java.io.Exception:内容长度错误预期x记忆量达到y量

时间:2012-05-02 16:27:44

标签: java android http post

我一直在尝试使用Android和NCBI blast website查询BioJava。我正在使用Eclipse和Android模拟器。当我将代码作为Android应用程序运行时,我收到以下错误:

W/System.err(533): java.io.IOException: An error occured submiting sequence to BLAST server. Cause: content-length promised 2000 bytes, but received 214

当我使用相同的代码并将其作为常规Java应用程序运行时,它可以完美运行。关于它可能是什么的任何想法?

1 个答案:

答案 0 :(得分:14)

当我尝试在Android中发出POST请求时,它也出现了。 如果你在标题中设置Content-Length并且实际内容的长度不同,那么它会在Android中抛出IOException(在普通的JDK中它有效,尽管它是错误的)

您可以使用以下代码重现Exception:

try {
    URL oracle = new URL("http://oasth.gr/tools/lineTimes.php");
    HttpURLConnection yc = (HttpURLConnection) oracle.openConnection();

    yc.setRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Linux i686; rv:2.0b12) Gecko/20110222 Firefox/4.0b12");
    yc.setRequestProperty("Referer",
            "http://oasth.gr/tools/lineTimes.php");
    yc.setRequestProperty("Accept-Language",
            "el-gr,el;q=0.8,en-us;q=0.5,en;q=0.3");
    yc.setRequestProperty("Accept-Charset",
            "ISO-8859-7,utf-8;q=0.7,*;q=0.7");

    // content length should be 29 !!
    yc.setRequestProperty("Content-Length", "1000");

    // content length is 29 !
    String parames = "bline=63&goes=a&lineStops=886";

    yc.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(yc.getOutputStream());

    wr.write(parames);
    wr.flush();
    Log.d(TAG, "" + yc.getResponseCode());

    BufferedReader in = new BufferedReader(new InputStreamReader(
            yc.getInputStream()));
    String inputLine;

    StringBuilder sbu = new StringBuilder();

    while ((inputLine = in.readLine()) != null)
        sbu.append(inputLine);

    wr.close();
    in.close();

} catch (IOException e) {
    e.printStackTrace();
    Log.e("getLinesArrival Exception", e.getMessage());
}

所以如果删除行

yc.setRequestProperty("Content-Length", "1000");

它会起作用!