首先是实现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);//第二个参数就是超时时间
本文介绍了一种在Android应用中自定义HTTP连接超时时间的方法。通过实现ServiceConnection接口并继承HttpTransportSE类,可以为SOAP Web服务请求设置特定的超时时间。
5034

被折叠的 条评论
为什么被折叠?



