package com.jqmobile.core.android.remote; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import com.jqmobile.core.android.ClientContext2; import com.jqmobile.core.http2.HttpSerializableObject; import com.jqmobile.core.http2.HttpUtils; import com.jqmobile.core.utils.json.JSONArray; import com.jqmobile.core.utils.json.JSONConvertor2; /** * <p>新框架远程访问工具</p> * * <p>Copyright: 版权所有 (c) 2002 - 2015<br> * Company: 久其</p> * * @author modi qq:411051729 * @version 2014年4月8日 */ public class RemoteManager { private final HttpUtils hu; private final String session; public RemoteManager(String remoteAddress, int remotePort, String remoteSession){ // this.session = remoteSession; this.session = null; String str = remoteAddress+":"+remotePort; if(!str.startsWith("http://")){ str = "http://"+str; } str = str+"/lbs-service"; this.hu = new HttpUtils(str, ClientContext2.WS_URI); } //================================================================ @SuppressWarnings("unchecked") public <T> T getService(Class<T> serviceClass){ return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new ClientInvocationHandler(serviceClass)); } class ClientInvocationHandler implements InvocationHandler{ private final Class<?> intf; /** * 构造函数 * @param serverURL 服务地址 * @param serviceURI 业务服务对相应的相对地址 * @param sessionID */ public ClientInvocationHandler(Class<?> intf) { this(intf, 10*1000); } public ClientInvocationHandler( Class<?> intf, int timeout) { this.intf = intf; hu.setTimeOut(timeout);; // HttpUtils.setTIMEOUT(timeout); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HttpSerializableObject hso = new HttpSerializableObject(); hso.setIntf(intf.getName()); hso.setMethod(method.getName()); hso.setSession(session); hso.setData(JSONConvertor2.serializableArray(args).toString()); // HttpSerializableObject result = hu.invoke(hso); if(null != result.getException()){ throw new Exception(); } JSONArray array = new JSONArray(result.getData()); return JSONConvertor2.unAutoSerializable(array.getJSONObject(0), method.getReturnType()); } } }