记录一个网易云IM和直播功能中,服务器API的Java调用代码


代码用到的开源工具:

fasterxml.jackson

apche-httpclient


代码位置

https://github.com/luoyuchou/NeteaseServerAPI


赶时间随手写的代码,网易云的API相当多,一般情况下用不完,所以只实现了一部分。

看起来有点复杂,不过好在一个请求一个类,个人看来也还算比较容易扩展。


网易云的公钥和私钥在APIHelper中获取。

main函数在$.java中

public class $ {	
//	@Resource
//	NeteaseNIMUserService service;	
	public static void main(String[] args) {
		NeteaseNIMUserService service = new NeteaseNIMUserServiceImpl(new APIHelper());
		ReqUserCreate req = new ReqUserCreate();
		req.setAccid("hello");
		req.setToken("hello");
		ResNIMInfo<ResUserInfo> res = service.createUser(req);
		if (res.getCode() == ResCode.SUCCESSFUL) {
			// success
		}
		service.createUserAsync(req, new ResultHandler<ResNIMInfo<ResUserInfo>>() {
			@Override
			public void handle(int status, ResNIMInfo<ResUserInfo> result) {
				if (result.getCode() == ResCode.SUCCESSFUL) {
					// success
				}
			}
		});
	}
}
适配了Spring,实际使用过程只需要Resource一下就好。由于是服务器到网易云的请求,支持同步和异步两种方式发送请求。


public final class APIHelper {
	public static final Charset APP_CHARSET = Charset.forName("UTF-8");
	/**
	 * 需要网易云的公钥和密钥
	 */
	private String appKey;
	private String appSecret;

	/**
	 * @Constructors APIHelper
	 * 
	 * 
	 * @Description TODO
	 */
	public APIHelper() {
		appKey = "";
		appSecret = "";
	}



使用Apache-HttpClient对请求和结果进行封装

static class HTTP {
		private static final CloseableHttpClient httpClient;
		static {
			httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
		}

		public static <T> void executeAsync(final NeteaseRequest req, final ResultHandler<T> hanlder, final TypeReference<T> typeReference) {
			/*
			 * 这里可以调用AsyncHttpClient 前提是需要加入apache-AsyncHttpClient包
			 */
			ThreadPoolScheduler.addTask(new Runnable() {

				@Override
				public void run() {
					CloseableHttpResponse response = execute(req);
					try {
						int httpStatus = response.getStatusLine().getStatusCode();
						String entity = EntityUtils.toString(response.getEntity());
						// System.out.println(entity);
						if (hanlder != null) {
							hanlder.handle(httpStatus);
							T t = null;
							if (StringUtils.isNotEmpty(entity) && typeReference != null) {
								t = APIHelper.JSON.toBean(entity, typeReference);
							}
							hanlder.handle(httpStatus, t);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (response != null) {
							try {
								response.close();
							} catch (IOException e) {
							}
						}
					}
				}
			});
		}

		public static CloseableHttpResponse execute(NeteaseRequest req) {
			if (req == null) {
				return null;
			}
			HttpPost httpPost = new HttpPost(req.getURL());
			Map<String, String> headers = req.getHeaders();
			if (headers != null && headers.size() > 0) {
				Set<Entry<String, String>> entries = headers.entrySet();
				for (Entry<String, String> entry : entries) {
					httpPost.setHeader(entry.getKey(), entry.getValue());
				}
			}
			String contentType = headers.get("Content-Type");
			if (StringUtils.isNotEmpty(contentType) && contentType.startsWith("application/x-www-form-urlencoded;")) {
				// 如果是表单提交
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				// 得到类对象
				Class<?> userCla = (Class<?>) req.getClass();
				/*
				 * 得到类中的所有属性集合
				 */
				Field[] fs = userCla.getDeclaredFields();
				try {

					Object val = null;
					for (int i = 0; i < fs.length; i++) {

						Field f = fs[i];
						f.setAccessible(true); // 设置些属性是可以访问的
						if (!Modifier.isStatic(f.getModifiers())) {
							val = f.get(req);
							if (val == null) {
								val = "";
							}
							nvps.add(new BasicNameValuePair(f.getName(), val.toString()));
						}
					}
					httpPost.setEntity(new UrlEncodedFormEntity(nvps, APP_CHARSET));
				} catch (IllegalArgumentException | IllegalAccessException e) {
					e.printStackTrace();
				}
			} else {
				// json提交
				httpPost.setEntity(new StringEntity(JSON.toJson(req), APP_CHARSET));
			}
			try {
				return httpClient.execute(httpPost);
			} catch (IOException e) {
			}
			return null;
		}
	}




使用fasterxml jackson对响应结果进行解析

static class JSON {
		private static final ObjectMapper jacksonMapper = new ObjectMapper();
		static {
			jacksonMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true);
			jacksonMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);
			jacksonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
			jacksonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			jacksonMapper.setSerializationInclusion(Include.NON_NULL);
		}

		@SuppressWarnings("unchecked")
		public static <T> T toBean(String jsonStr, TypeReference<T> typeReference) {
			try {
				return jacksonMapper.readValue(jsonStr, typeReference);
			} catch (IOException e) {
				try {
					ParameterizedType type = (ParameterizedType) typeReference.getType();
					return (T) getClass(type.getRawType()).newInstance();
				} catch (Exception e1) {
					return null;
				}
			}
		}

		private static final String TYPE_NAME_PREFIX = "class ";

		private static String getClassName(Type type) {
			if (type == null) {
				return "";
			}
			String className = type.toString();
			if (className.startsWith(TYPE_NAME_PREFIX)) {
				className = className.substring(TYPE_NAME_PREFIX.length());
			}
			return className;
		}

		private static Class<?> getClass(Type type) throws ClassNotFoundException {
			String className = getClassName(type);
			if (className == null || className.isEmpty()) {
				return null;
			}
			return Class.forName(className);
		}

		public static String toJson(Object obj) {
			try {
				return jacksonMapper.writeValueAsString(obj);
			} catch (JsonProcessingException e) {
			}
			return "";
		}
	}



话说写完好久都不知道有没有用到什么设计模式,有没有用对什么的。好丢人。有空赶紧再补一遍设计模式去

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值