Android中调用WebService抛出Connection reset by peer异常

最近在做的项目中用到了WebService,因为Android中没有提供直接调用WebService的Api,我就使用了 ksoap,但是在使用过程中遇到了一个奇怪的BUG:

请求一次WebService之后,什么都不做,静待1分钟之后,再次请求这个WebService时就会抛出以下异常:

06-17 15:11:07.869: W/System.err(10915): java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)

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)

06-17 15:11:07.879: W/System.err(10915): at java.net.PlainSocketImpl.write(PlainSocketImpl.java:508)

06-17 15:11:07.879: W/System.err(10915): at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:46)

06-17 15:11:07.879: W/System.err(10915): at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:270)

06-17 15:11:07.879: W/System.err(10915): at java.io.BufferedOutputStream.flushInternal(BufferedOutputStream.java:185)

06-17 15:11:07.879: W/System.err(10915): at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:85)

06-17 15:11:07.879: W/System.err(10915): at libcore.net.http.FixedLengthOutputStream.flush(FixedLengthOutputStream.java:49)

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)。

问题解决了,不是用最好的办法!

你可能感兴趣的:(Android中调用WebService抛出Connection reset by peer异常)