重构http请求
下午对公司中http请求的代码进行了重构,之前的每个请求都需要写一个post方法,不相同的只是请求的参数.而且代码中有很多累赘的代码,比如每次请求都需要重新new一个DefaultHttpClient,在finally中每次都需要shutdown一下.之前看过的一本重构书籍中也提到了对于这样的代码存在的臭味.所以下午就对之前的代码进行了重构并根据apache httpclient官网重新写了一个单例的DefaultHttpClient类.单例类如下:
@SuppressWarnings("unchecked")public static Object post(String url, Object object) {Object o = null;if (url == null || url.length() <= 0)throw new ServiceException("Url can not be null.");url = BASE_URL + url;String temp = url.toLowerCase();if (!temp.startsWith("http://") && !temp.startsWith("https://"))url = "http://" + url;url = URI.create(url).toASCIIString();DefaultHttpClient httpClient = (DefaultHttpClient) SingletonClient.getHttpClient();try {HttpPost httpMethod = new HttpPost(url);httpMethod.setHeader("key", "Aj9eZHdle73nx1Zi1kX5");if (object instanceof Map) {InputStreamEntity reqEntity = new InputStreamEntity(Streams.wrap(Json.toJson(object).getBytes("UTF-8")), -1);reqEntity.setContentType("binary/octet-stream");reqEntity.setChunked(true);reqEntity.setContentEncoding("UTF-8");httpMethod.setEntity(reqEntity);} else if (String.class.isAssignableFrom(object.getClass())) {httpMethod.setEntity(new StringEntity(Json.toJson(object.toString())));} else {throw new ServiceException("illegal request arguments");}HttpResponse response = httpClient.execute(httpMethod);int status=response.getStatusLine().getStatusCode();if (status != org.apache.http.HttpStatus.SC_OK) {LOG.warn("Http Satus:" + status + ",Url:" + url);if (status >= 500 && status < 600)throw new IOException("Remote service<" + url+ "> respose a error, status:" + status);return null;}HttpEntity entity = response.getEntity();o = EntityUtils.toString(entity);EntityUtils.consume(entity);} catch (Exception e) {throw new ServiceException("error!");} finally {//httpClient.getConnectionManager().shutdown();}return o;}上面的代码中json解析采用的是Nutz框架中的Json类(性能不亚于google的Gson).这段代码现在只支持Map,String类型参数的请求,以后如有需求还会进行重构.暂时是可以应对需求的.我们现在只需要传过去对象或者字符串在另一个项目中进行数据库查找验证.在这个项目中只需要获取请求是否成功即可.好了,要下班了.