首先是实现ServiceConnection接口,实现其中的一系列方法,代码如下:
package com.miteno.fpsearch.utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.ksoap2.transport.ServiceConnection; /** * 继承了HttpTransportSE ,添加请求超时的操作 * * @author wsx * */ public class ServiceConnectionSE implements ServiceConnection { private HttpURLConnection connection; public ServiceConnectionSE(String url) throws IOException { this.connection = ((HttpURLConnection) new URL(url).openConnection()); this.connection.setUseCaches(false); this.connection.setDoOutput(true); this.connection.setDoInput(true); } public void connect() throws IOException { this.connection.connect(); } public void disconnect() { this.connection.disconnect(); } public void setRequestProperty(String string, String soapAction) { this.connection.setRequestProperty(string, soapAction); } public void setRequestMethod(String requestMethod) throws IOException { this.connection.setRequestMethod(requestMethod); } public OutputStream openOutputStream() throws IOException { return this.connection.getOutputStream(); } public InputStream openInputStream() throws IOException { return this.connection.getInputStream(); } public InputStream getErrorStream() { return this.connection.getErrorStream(); } // 设置连接服务器的超时时间,毫秒级,此为自己添加的方法 public void setConnectionTimeOut(int timeout) { this.connection.setConnectTimeout(timeout); } }
接下来是要继承HttpTransportSE 类,覆写其中的getServiceConnection方法,代码如下:
package com.miteno.fpsearch.utils; import java.io.IOException; import org.ksoap2.transport.HttpTransportSE; import org.ksoap2.transport.ServiceConnection; /** * 继承了HttpTransportSE ,添加请求超时的操作 * * @author wsx * */ public class MyAndroidHttpTransport extends HttpTransportSE { private int timeout = 30000; // 默认超时时间为30s public MyAndroidHttpTransport(String url) { super(url); } public MyAndroidHttpTransport(String url, int timeout) { super(url); this.timeout = timeout; } @Override protected ServiceConnection getServiceConnection() throws IOException { ServiceConnectionSE serviceConnection = new ServiceConnectionSE(url); serviceConnection.setConnectionTimeOut(timeout); return serviceConnection; } }
然后接下来是使用:
//AndroidHttpTransport httpTranstation = new AndroidHttpTransport(serviceUrl + "?WSDL"); 这里注释掉,原始的调用方法 MyAndroidHttpTransport httpTranstation = new MyAndroidHttpTransport(serviceUrl + "?WSDL", 1000 * 80);
补充内容:
今天发现ksoap2-android-assembly-3.1.0-jar-with-dependencies.jar把这个问题修复了可以直接来设置超时时间了
HttpTransportSE se=new HttpTransportSE(url, timeout);//第二个参数就是超时时间
近来的在公司做的二次开发,原有的项目底层是用的HttpTransportSE和.net服务器进行通讯的,但是默认的网络超时时间太长了(好像是10秒),找了一下,发现这边文章博主写的蛮不错的,于是收集一下,后面还打算实现线程池存储每次网络请求,并且实现可以在线程池中取消已经发送的请求并释放相关资源。好吧,今天时间就到这吧,改日再战!