使用HttpURLConnection getOutputStream()的Intermitent FileNotFoundException

时间:2013-06-20 14:00:06

标签: android

我在发布到网络服务器并阅读响应时遇到间歇性问题,通常在手机使用3G / Edge连接时,无论是在2.3还是4.1上。

我的代码是:

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");    
    conn.setRequestProperty("ContentLength",Integer.toString(JSONString.getBytes().length));
conn.connect();

//send request
BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream(), 2048);
bos.write(JSONString.getBytes());
bos.flush();
bos.close();

//read response
br = new BufferedReader(new InputStreamReader(conn.getInputStream(),Charset.forName("ISO-8859-1")),8192);
String line;
response = new StringBuffer();

while ( (line = br.readLine()) != null )        
    response.append(line);

代码几乎总是有效,但有时在尝试构建BufferedReader时(在getInputStream()上)失败,产生以下异常:

java.io.FileNotFoundException: http://www.myserver.com/test/ws/login.php
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
at com.myapp.android.NetWorker.sendPost(NetWorker.java:59)
at com.myapp.android.LoginSvc.onHandleIntent(LoginSvc.java:72)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.os.HandlerThread.run(HandlerThread.java:60)

我尝试删除setDoOutput(),但没有成功。我无法通过使用其他软件(例如Postman)来发送完全相同的POST有效负载来重现该问题。对此有何不妥?

提前致谢:)

PS:我尝试过以下解决方案,但没有成功: ħ

  1. FileNotFoundException for HttpURLConnection in Ice Cream Sandwich
  2. FileNotFoundException on Android version > 2.3

0 个答案:

没有答案