当前位置: 代码迷 >> Web前端 >> HttpURLConnection与URL-接口的运用
  详细解决方案

HttpURLConnection与URL-接口的运用

热度:134   发布时间:2012-11-01 11:11:33.0
HttpURLConnection与URL---接口的应用

一版XXX中的更新内存的接口应用:

?

一、定义一个有返回值的接口:?

/**
  * 后台更新调用此方法更新前台内存数据
  * @author lvwenyong
  * @date 2011-5-31 下午01:42:16
 */
@SuppressWarnings("unchecked")
public void reload(){
	try {
		Class clazz= Class.forName(getRequest().getParameter("cn"));
		Method m = clazz.getDeclaredMethod("load"+clazz.getSimpleName().replace("Ctrl", ""));
		m.invoke(clazz) ;
		outPrint("0", "text/HTML");
	} catch (Exception e) {
		e.printStackTrace();
		log.error("MemoryAction更新内存失败",e);
		outPrint("1", "text/HTML");
	} 
}


/*PrintWriter输出流*/
protected void outPrint(String content,String contentType) {
	HttpServletResponse resp = getResponse();
	resp.setCharacterEncoding("utf-8");
	resp.setContentType(contentType);
	try {
		PrintWriter out = resp.getWriter();
		out.print(content);
		out.flush();
		out.close();
	} catch (IOException e) {
		e.printStackTrace();
		log.error("", e);
	}
}

?

二、调用接口,根据返回值判断

/**
 * 更新b2cPlatform(前台)内存
 * @param cn
 * @return 0成功 1失败
 * @throws IOException
 * @author lvwenyong
 * @date 2011-6-7 下午01:18:20
 */
public static String clientUpdate(String cn) throws IOException {
	BufferedReader br = null;
	try {
		URL url = new URL(ConfigCtrl
				.getConfigValue("client_memory_reload_url")
				// "http://192.168.10.123:8888"
				+ "/b2cPlatform/memory_reload.action?cn=" + Memory.valueOf(cn).getName());
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.getContent();
//			System.out.println("type======" + conn.getContentType());
		br = new BufferedReader(
				new InputStreamReader(conn.getInputStream()));
		String state =  br.readLine();//0成功 1失败
		return state;
	} finally {
		if (br != null)
			br.close();
	}
}

?

?三、辅助类

public enum Memory {
	Dictionary {
		@Override
		public String getName() {
			return "com.hanpeng.base.util.memoryCtrl.DictionaryCtrl";
		}
	},
	Config {
		@Override
		public String getName() {
			return "com.hanpeng.base.util.memoryCtrl.ConfigCtrl";
		}
	} ,
	BussinessRole{
		public String getName() {
			return "com.hanpeng.base.util.memoryCtrl.BussinessRoleCtrl";
		}
	},
	BussinessRolePriv{
		public String getName() {
			return "com.hanpeng.base.util.memoryCtrl.BussinessRolePrivCtrl";
		}
	}
	,
	Alipay{
		public String getName() {
			return "com.hanpeng.base.util.memoryCtrl.AlipayInfoCtrl";
		}
	}
	,
	Tenpay{
		public String getName() {
			return "com.hanpeng.base.util.memoryCtrl.TenpayInfoCtrl";
		}
	}
	;
	
	public abstract String getName();
	
}
?

?

  相关解决方案