安卓调用webservice两个工具类
/* okHttp调用WebService思路:post拼接好的请求体 踩坑:1.mediaType没写导致的请求不成功 2.url写的不是调用后的实际url<打开接口方法链接后,地址栏的url> 3.读取超时,貌似是没有配置Application的原因. 4.同步方法可以返回数据,异步不行. 原因:在网络请求完成对响应数据进行包装,return null;导致的异步响应方法接收到的数据总是null. 解决办法:将请求网络return response; 5.*/import com.zhy.com.zhy.java.util.Map;import okok* Created by ray on 2018/2/27. * okHttp调用WebService */public class CallWebService { /** * 获取网络数据 * * @param methods 方法名 * @param map 参数 */ public static String getResultData(String methods, Map map) { StringBuilder stringBuilder = null; if (map != null) { stringBuilder = new StringBuilder(); for (Map.Entry entry : map.entrySet()) { stringBuilder.append("<").append(entry.getKey()).append(">").append(entry.getValue()).append("").append(entry.getKey()).append(">"); } } String xml = "\n" + "\n" + " XXXXXX\n" + " XXXXXX\n" + " \n" + " \n" + " \n" + " <" + methods + " xmlns=\" + stringBuilder + " " + methods + ">\n" + " \n" + ""; RequestCall build = OkHttpUtils.postString() .url("+ methods) .mediaType(MediaType.parse("text/xml; charset=utf-8")) .addHeader("SOAPAction", "+ methods) .addHeader("Content-Type", "text/xml; charset=utf-8") .content(xml) .build().connTimeOut(30000).readTimeOut(5000); try { Response execute = build.execute(); String string = execute.body().string(); return string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1); } catch (Exception e) { e.printStackTrace(); } return null; }}---------------------------------------------------------------------------------------Appleation配置ClearableCookieJar cookieJar1 = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);//CookieJarImpl cookieJar1 = new CookieJarImpl(new MemoryCookieStore());OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000L, TimeUnit.MILLISECONDS).readTimeout(10000L, TimeUnit.MILLISECONDS).addInterceptor(new LoggerInterceptor("TAG")).cookieJar(cookieJar1).hostnameVerifier(new HostnameVerifier(){ @Override public boolean verify(String hostname, SSLSession session) { return true; }}).sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager).build();OkHttpUtils.initClient(okHttpClient);------------------------------------------------------------------------gradle配置 implementation 'com.zhy:okandroid.os.Handler;import android.os.Message;import android.support.v4.util.SimpleArrayMap;import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObject;import org.ksoap2.serialization.SoapSerializationEnvelope;import org.ksoap2.transport.HttpTransportSE;import org.kxml2.kdom.Element;import org.kxml2.kdom.Node;import org.xmlpull.v1.XmlPullParserException;import java.io.IOException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * 访问 WebService 的工具类 */public class WebServiceUtil { // 命名空间 private static final String NAMESPACE = "your namespace"; // WebService 服务器地址 private static final String ENDPOINT = "your address"; // 一般自己公司开发都是需要身份验证的 // 身份验证方法名 private static final String ID_HEADERNAME = "verify method"; // 身份验证 key private static final String ID_NAME_PARAM = "verify key1"; // 身份验证 value private static final String ID_NAME_VALUE = "verify value1"; // 身份验证 key private static final String ID_PASSWORD_PARAM = "verify key2"; // 身份验证 value private static final String ID_PASSWORD_VALUE = "verify value2"; // 访问的服务器是否由 dotNet 开发 public static boolean isDotNet = true; // 线程池的大小 private static int threadSize = 5; // 创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程 private static ExecutorService threadPool = Executors.newFixedThreadPool(threadSize); // 连接响应标示 public static final int SUCCESS_FLAG = 0; public static final int ERROR_FLAG = 1; /** * 调用 WebService 接口 * * @param methodName WebService 的调用方法名 * @param mapParams WebService 的参数集合,可以为 null * @param reponseCallBack 服务器响应接口 */ public static void call(final String methodName, SimpleArrayMap mapParams, final ResponseCallBack reponseCallBack) { // 创建 HttpTransportSE 对象,传递 WebService 服务器地址 final HttpTransportSE transport = new HttpTransportSE(ENDPOINT); transport.debug = true; // 身份验证(如果需要的话) Element[] header = new Element[1]; // 传入命名空间与验证的方法名 header[0] = new Element().createElement(NAMESPACE, ID_HEADERNAME); // 创建参数 1 Element userName = new Element().createElement(NAMESPACE, ID_NAME_PARAM); userName.addChild(Node.TEXT, ID_NAME_VALUE); header[0].addChild(Node.ELEMENT, userName); // 创建参数 2 Element password = new Element().createElement(NAMESPACE, ID_PASSWORD_PARAM); password.addChild(Node.TEXT, ID_PASSWORD_VALUE); header[0].addChild(Node.ELEMENT, password); // 创建 SoapObject 对象用于传递请求参数 final SoapObject soapObject = new SoapObject(NAMESPACE, methodName); // 添加参数 if (mapParams != null) { for (int index = 0; index < mapParams.size(); index++) { String key = mapParams.keyAt(index); // 多数情况下,传递的参数都为 String 类型,不过少数情况下会有 boolean 类型,所以用 Object 代替 Object value = mapParams.get(key); soapObject.addProperty(key, value); } } // 实例化 SoapSerializationEnvelope,传入 WebService 的 SOAP 协议的版本号 // 这里有 VER10 VER11 VER12 三种版本,根据自己需要填写 final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.headerOut = header; // 身份验证(如果需要的话) envelope.dotNet = isDotNet; // 设置是否调用的是 .Net 开发的 WebService envelope.bodyOut = soapObject; // 传递参数 //envelope.setOutputSoapObject(soapObject);// 与上一句等价 // 用于与主线程通信的 Handler final Handler responseHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); // 根据消息的 arg1 值判断调用哪个接口 if (msg.arg1 == SUCCESS_FLAG) { reponseCallBack.onSuccess((String) msg.obj); } else { reponseCallBack.onError((Exception) msg.obj); } } }; // 提交一个子线程到线程池并在此线种内调用 WebService if (threadPool == null || threadPool.isShutdown()) { threadPool = Executors.newFixedThreadPool(threadSize); } threadPool.submit(new Runnable() { @Override public void run() { String result = null; try { // 解决 EOFException System.setProperty(""false"); // 连接服务器,有的服务可能不需要传递 NAMESPACE + methodName,第一个参数传递 null transport.call(null, envelope); if (envelope.getResponse() != null) { // 获取服务器响应返回的 SoapObject SoapObject object = (SoapObject) envelope.bodyIn; result = object.getProperty(0).toString(); } } catch (IOException e) { // 当 call 方法的第一个参数为 null 时会有一定的概念抛 IO 异常 // 因此需要需要捕捉此异常后用命名空间加方法名作为参数重新连接 // e.printStackTrace(); try { transport.call(NAMESPACE + methodName, envelope); if (envelope.getResponse() != null) { // 获取服务器响应返回的 SoapObject SoapObject object = (SoapObject) envelope.bodyIn; result = object.getProperty(0).toString(); } } catch (Exception e1) { // e1.printStackTrace(); responseHandler.sendMessage(responseHandler.obtainMessage(0, ERROR_FLAG, 0, e1)); } } catch (XmlPullParserException e) { // e.printStackTrace(); responseHandler.sendMessage(responseHandler.obtainMessage(0, ERROR_FLAG, 0, e)); } finally { // 将获取的消息利用 Handler 发送到主线程 responseHandler.sendMessage(responseHandler.obtainMessage(0, SUCCESS_FLAG, 0, result)); } } }); } /** * 设置线程池的大小 * * @param threadSize */ public static void setThreadSize(int threadSize) { WebServiceUtil.threadSize = threadSize; threadPool.shutdownNow(); threadPool = Executors.newFixedThreadPool(WebServiceUtil.threadSize); } /** * 服务器响应接口,在响应后需要回调此接口 */ public interface ResponseCallBack { void onSuccess(String result); void onError(Exception e); }}----------------------------------------------------------------------------------------------Activity中使用--------------------private void request() { SimpleArrayMap map = new SimpleArrayMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); WebServiceUtil.call("method name", map, new WebServiceUtil.ResponseCallBack() { @Override public void onSuccess(String result) { // 请求成功 } @Override public void onError(Exception e) { // 请求失败 } });}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~