【发布时间】:2011-04-28 20:39:14
【问题描述】:
我的应用程序中有一个创建 HttpURLConnection 的 AsyncTask。接下来,它调用 getOutputStream(),写入一些字节,刷新并关闭。然后它调用getResponseCode() 和getInputStream()。如果我需要发布代码,我可以,但我想我会保持小问题。
当我第一次运行时,我得到一个 200 响应代码,并且我得到了正确的输入流。
当我第二次到第五次运行此程序时,我得到一个新线程(可在 DDMS 视图中查看),我收到一个 500 响应代码,并在获取输入流时收到一个 IOException。
当我第六次或更多次调用它时,没有创建新线程,我仍然得到 500 响应代码和 IOException。
我可以在这里寻找什么?它总是工作一次,再也不会。有没有其他人看过这个?我完全被难住了。
这是 MINIMAL 代码(我删除了 try/catch、变量声明、应用特定内容等):
protected String doInBackground(String... params)
{
connectURL = new URL(sWebPath);
conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "MyAppAgent");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
// Setup my post as a string s.
conn.setRequestProperty("Content-Length", String.valueOf(s.length()));
conn.connect();
DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream());
dataStream.writeBytes(s);
dataStream.flush();
dataStream.close();
dataStream = null;
// 200 1st time only, 500 after that.
responseCode = conn.getResponseCode();
// Works 1st time only, IO error after that
DataInputStream dis = new DataInputStream(conn.getInputStream());
byte[] data = new byte[16384];
int len = dis.read(data, 0, 16384);
dis.close();
conn.disconnect();
response = new String(data, 0, len);
// do whatever with my response
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
// Now I call a Toast message on the original context used to
// create this AsyncTask.
}
// The onClickListener of a button calls this AsyncTask (TierRequest class) with only two lines
TierRequest t = new TierRequest(WhateverMyCurrentActivityIs.this);
t.execute(A_Constant_Indicating_The_Type_Of_Post);
【问题讨论】:
-
请完成最小代码。
-
尽量不要每次都在流上调用 close()。不知道有什么后果,所以我不会提供这个作为答案,但在过去,当我多次与服务器通信时,这对我有用。
-
我发布了最少的代码。我删除了 try/catch 块、变量声明和特定于应用程序的处理,例如如何处理响应等。除此之外,如果您在此处看不到应有的内容,那么我错过了!
-
您能否发布您调用 AsyncTask 的 execute() 方法的部分的代码?你怎么叫它多次?
-
你在打什么 URI?使用不同的 URI(如 google.com)时是否会出现相同的错误?
标签: android android-asynctask httpurlconnection