记录一个网易云IM和直播功能中,服务器API的Java调用代码
2017-09-14 02:02
435 查看
代码用到的开源工具:
fasterxml.jackson
apche-httpclient
代码位置
https://github.com/luoyuchou/NeteaseServerAPI
赶时间随手写的代码,网易云的API相当多,一般情况下用不完,所以只实现了一部分。
看起来有点复杂,不过好在一个请求一个类,个人看来也还算比较容易扩展。
网易云的公钥和私钥在APIHelper中获取。
main函数在$.java中
public class $ {
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 "";
}
}
话说写完好久都不知道有没有用到什么设计模式,有没有用对什么的。好丢人。有空赶紧再补一遍设计模式去
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 "";
}
}
话说写完好久都不知道有没有用到什么设计模式,有没有用对什么的。好丢人。有空赶紧再补一遍设计模式去
相关文章推荐
- 意外作出了一个javascript的服务器,可以通过js调用并执行任何java(包括 所有java 内核基本库)及C#类库,并最终由 C# 执行你提交的javascript代码! 不敢藏私,特与大家分
- 意外作出了一个javascript的服务器,可以通过js调用并执行任何java(包括 所有java 内核基本库)及C#类库,并最终由 C# 执行你提交的javascript代码! 不敢藏私,特与大家分
- 发现了一个腾讯微博代码BasicAPI .java的里面的一个很低级bug,居然用==比较字符串
- Cocos2d-x3.3RC0通过JNI调用Android的Java层代码,实现分享功能
- java中的post请求之raw请求--微信api调用java代码示例
- 一个初级例子讲述C和CPP在JNI中调用安卓Java代码
- Jetty的配置、部署与API使用——(2)通过Jetty的Java API运行一个Jetty服务器
- 库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
- 库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
- 使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
- Android NDK学习记录(二):C/C++调用Java代码
- [原]java中的post请求之raw请求--微信api调用java代码示例
- java中查找一个方法都是哪些方法调用的代码
- windows下流媒体nginx-rmtp-module服务器搭建及java程序调用fmpeg将rtsp转rtmp直播流【转】
- Linux内核分析:使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
- JAVA功能代码《3》----获取Java现在正调用的方法名
- JAVA功能代码《3》----获取Java现在正调用的方法名
- 使用java调用C语言的方法,让java获取串口数据并生成一个String对象的代码。
- 使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
- Java 实现在线翻译功能 调用微软Bing API