好记性,不如烂笔头。
简介
聊天是个很常用的应用,但是很多时候,如何快速的沟通,这就需要用点心思了,下面看看我们 Java 如何调用 环信的接口实现用户注册通信。要使用环信的接口实现通信,就要活得环信的秘钥,但是这个是要掏钱的,很多时候,我们都不想去掏钱,那么如何去HTTPS 请求变为HTTP请求,就显得很有必要,那么现在看看如何实现去HTTPS请求。
JAVA去HTTPS代码实现
资源 http://download.csdn.net/detail/supingemail/8991533 中有详细的实现,具体的细节可以参加这个来实现。
主要去 HTTPS 的代码是:
private static String httpsPostRequest(String url, byte[] requestData) throws Exception {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());
HttpsURLConnection httpsConn = null;
StringBuffer sBuffer = new StringBuffer(300);
try {
httpsConn = (HttpsURLConnection) new URL(url).openConnection();
httpsConn.setHostnameVerifier(new TrustAnyHostnameVerifier());
httpsConn.setSSLSocketFactory(sc.getSocketFactory());
httpsConn.setConnectTimeout(45000); // 设置的超时时间大于45秒
httpsConn.setDoInput(true);
httpsConn.setDoOutput(true);
BufferedOutputStream hurlBufOus = new BufferedOutputStream(httpsConn.getOutputStream());
hurlBufOus.write(requestData);
hurlBufOus.flush();
hurlBufOus.close();
httpsConn.connect();
//System.out.println(httpsConn.getResponseCode());
BufferedReader in = null;
String inputLine = null;
in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), CHARACTER_ENCODING));
while ((inputLine = in.readLine()) != null) {
sBuffer.append(inputLine);
}
in.close();
} catch (Exception e) {
throw e;
} finally {
if (httpsConn != null) {
httpsConn.disconnect();
}
}
return sBuffer.toString();
}
主要的实现就是这些,但是实际上又有很多的操作,详细的请参见资料 :http://download.csdn.net/detail/supingemail/8991533
环信即时通信
先看环信的 API 文档:http://docs.easemob.com/doku.php?id=start:100serverintegration:20users
详细介绍了如何使用api来集成现有的设备实现通信机制。
核心代码实现:
/**
*
* @param requestUserUrl:用户访问的url
* @param HuanXinToken:环信的token
* @param userName:用户名
* @param passWord:密码
*/
public static void getHuanXinInfo(String requestUserUrl,String HuanXinToken,String userName,String passWord){
HashMap<String, String> params =new HashMap<String, String>();
params.put("username", userName);
params.put("password", passWord);
HashMap<String, String> header =new HashMap<String, String>();
String contentType ="application/json";
header.put("Authorization", "Bearer "+HuanXinToken+"");
header.put("Content-Type", contentType);
String charsetName = "UTF-8";
String postBody = "{\"username\":\""+userName+"\",\"password\":\""+passWord+"\"}";
String result = HttpsClientUtils.getContentPost(requestUserUrl, params, header, charsetName, postBody, contentType);
System.out.println(result);
}
用到的相关类和 jar 文件在资料中有,需要的去资料中下载。。。
到此,去https请求变成http请求以及环信用户注册都已经完成了。。。