最近在作的項目中用到了WebService,由於Android中沒有提供直接調用WebService的Api,我就使用了 ksoap,可是在使用過程當中遇到了一個奇怪的BUG:
請求一次WebService以後,什麼都不作,靜待1分鐘以後,再次請求這個WebService時就會拋出如下異常:
java
06-17 15:11:07.869: W/System.err(10915): java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)android
06-17 15:11:07.879: W/System.err(10915): at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:510)服務器
06-17 15:11:07.879: W/System.err(10915): at libcore.io.IoBridge.sendto(IoBridge.java:479)google
06-17 15:11:07.879: W/System.err(10915): at java.net.PlainSocketImpl.write(PlainSocketImpl.java:508)spa
06-17 15:11:07.879: W/System.err(10915): at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:46).net
06-17 15:11:07.879: W/System.err(10915): at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:270)code
06-17 15:11:07.879: W/System.err(10915): at java.io.BufferedOutputStream.flushInternal(BufferedOutputStream.java:185)get
06-17 15:11:07.879: W/System.err(10915): at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:85)it
06-17 15:11:07.879: W/System.err(10915): at libcore.net.http.FixedLengthOutputStream.flush(FixedLengthOutputStream.java:49)io
06-17 15:11:07.879: W/System.err(10915): at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:188)
06-17 15:11:07.879: W/System.err(10915): at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
06-17 15:11:07.879: W/System.err(10915): at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
06-17 15:11:07.879: W/System.err(10915): at com.mycos.mobile.util.WebServiceUtils.getObject(WebServiceUtils.java:144)
06-17 15:11:07.879: W/System.err(10915): at com.mycos.mobile.util.WebServiceUtils.getString(WebServiceUtils.java:63)
06-17 15:11:07.879: W/System.err(10915): at com.mycos.mobile.util.WebServiceAsyncRunner$1.run(WebServiceAsyncRunner.java:38)
06-17 15:11:07.879: W/System.err(10915): Caused by: libcore.io.ErrnoException: sendto failed: ECONNRESET (Connection reset by peer)
06-17 15:11:07.879: W/System.err(10915): at libcore.io.Posix.sendtoBytes(Native Method)
06-17 15:11:07.879: W/System.err(10915): at libcore.io.Posix.sendto(Posix.java:151)
06-17 15:11:07.879: W/System.err(10915): at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:177)
06-17 15:11:07.879: W/System.err(10915): at libcore.io.IoBridge.sendto(IoBridge.java:477)
06-17 15:11:07.879: W/System.err(10915): ... 12 more
從堆棧信息來看是鏈接被服務器重置了,可爲何連續請求沒問題,靜待一分鐘後再請求卻會被重置呢?
想了好久,想不出究竟是什麼問題致使了這個異常,只好使用另一種辦法來繞過了這個異常:
模擬HttpClient的重試機制,爲WebService請求也增長重試機制,若是拋出java.net.SocketException以後,再連續請求兩次請求(加上第一次,最大重試次數爲3)。
問題解決了,不是用最好的辦法!