如何通过SpringBoot,创建融云账户?

首先需要在pom文件里导包
 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->

        <dependency>

            <groupId>org.apache.httpcomponents</groupId>

            <artifactId>httpclient</artifactId>

            <version>4.5.3</version>

        </dependency>
        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
        </dependency>

在创建如图的几个类



public class CodeUtil {
	
	public static String hexSHA1(String value) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(value.getBytes("utf-8"));
			byte[] digest = md.digest();
			return byteToHexString(digest);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	public static String byteToHexString(byte[] bytes) {
		return String.valueOf(Hex.encodeHex(bytes));
	}
}
public class GsonUtil {

	private static Gson gson = new GsonBuilder().disableHtmlEscaping().create();

	public static String toJson(Object obj, Type type) {
		return gson.toJson(obj, type);
	}

	public static Object fromJson(String str, Type type) {
		return gson.fromJson(str, type);
	}

	public static Object fromJson(Reader reader, Type type) {
		return gson.fromJson(reader, type);
	}
}
public enum HostType {
	API("http://api.cn.ronghub.com"), SMS("http://api.sms.ronghub.com");
	private String type;

	private HostType(String type) {
		this.type = type;
	}

	public static HostType getType(String state) {
		for (HostType deviceType : HostType.values()) {
			if (deviceType.type.equalsIgnoreCase(state)) {
				return deviceType;
			}
		}
		throw new RuntimeException(state + " is not a valid Host Type!");
	}

	public String getStrType() {
		return type;
	}
}
public class HttpUtil {

	private static final String APPKEY = "RC-App-Key";
	private static final String NONCE = "RC-Nonce";
	private static final String TIMESTAMP = "RC-Timestamp";
	private static final String SIGNATURE = "RC-Signature";

	private static SSLContext sslCtx = null;
	static {

		try {
			sslCtx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			sslCtx.init(null, new TrustManager[] { tm }, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

			@Override
			public boolean verify(String arg0, SSLSession arg1) {
				// TODO Auto-generated method stub
				return true;
			}

		});

		HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());

	}

	// 设置body体
	public static void setBodyParameter(StringBuilder sb, HttpURLConnection conn) throws IOException {
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.writeBytes(sb.toString());
		out.flush();
		out.close();
	}

	public static HttpURLConnection CreateGetHttpConnection(String uri) throws MalformedURLException, IOException {
		URL url = new URL(uri);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(30000);
		conn.setRequestMethod("GET");
		return conn;
	}

	public static void setBodyParameter(String str, HttpURLConnection conn) throws IOException {
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.write(str.getBytes("utf-8"));
		out.flush();
		out.close();
	}

	public static HttpURLConnection CreatePostHttpConnection(HostType hostType, String appKey, String appSecret, String uri,
			String contentType) throws MalformedURLException, IOException, ProtocolException {
		String nonce = String.valueOf(Math.random() * 1000000);
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
		StringBuilder toSign = new StringBuilder(appSecret).append(nonce).append(timestamp);
		String sign = CodeUtil.hexSHA1(toSign.toString());
		uri = hostType.getStrType() + uri;
		URL url = new URL(uri);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setUseCaches(false);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setInstanceFollowRedirects(true);
		conn.setConnectTimeout(30000);
		conn.setReadTimeout(30000);
		
		conn.setRequestProperty(APPKEY, appKey);
		conn.setRequestProperty(NONCE, nonce);
		conn.setRequestProperty(TIMESTAMP, timestamp);
		conn.setRequestProperty(SIGNATURE, sign);
		conn.setRequestProperty("Content-Type", contentType);

		return conn;
	}

	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}

	public static String returnResult(HttpURLConnection conn) throws Exception, IOException {
		InputStream input = null;
		if (conn.getResponseCode() == 200) {
			input = conn.getInputStream();
		} else {
			input = conn.getErrorStream();
		}
		String result = new String(readInputStream(input), "UTF-8");
		return result;
	}

}
 
public class RongCloud {

	private static ConcurrentHashMap<String, RongCloud> rongCloud = new ConcurrentHashMap<String,RongCloud>();
	
	public User user;
//	public Message message;
//	public Wordfilter wordfilter;
//	public Group group;
//	public Chatroom chatroom;
//	public Push push;
//	public SMS sms;

	private RongCloud(String appKey, String appSecret) {
		user = new User(appKey, appSecret);
//		message = new Message(appKey, appSecret);
//		wordfilter = new Wordfilter(appKey, appSecret);
//		group = new Group(appKey, appSecret);
//		chatroom = new Chatroom(appKey, appSecret);
//		push = new Push(appKey, appSecret);
//		sms = new SMS(appKey, appSecret);

	}

	public static RongCloud getInstance(String appKey, String appSecret) {
		if (null == rongCloud.get(appKey)) {
			rongCloud.putIfAbsent(appKey, new RongCloud(appKey, appSecret));
		}
		return rongCloud.get(appKey);
	}
	 
}
public class TokenResult {
	// 返回码,200 为正常.如果您正在使用开发环境的 AppKey,您的应用只能注册 100 名用户,达到上限后,将返回错误码 2007.如果您需要更多的测试账户数量,您需要在应用配置中申请“增加测试人数”。
	Integer code;
	// 用户 Token,可以保存应用内,长度在 256 字节以内.用户 Token,可以保存应用内,长度在 256 字节以内。
	String token;
	// 用户 Id,与输入的用户 Id 相同.用户 Id,与输入的用户 Id 相同。
	String userId;
	// 错误信息。
	String errorMessage;
	
	public TokenResult(Integer code, String token, String userId, String errorMessage) {
		this.code = code;
		this.token = token;
		this.userId = userId;
		this.errorMessage = errorMessage;
	}
	
	/**
	 * 设置code
	 *
	 */	
	public void setCode(Integer code) {
		this.code = code;
	}
	
	/**
	 * 获取code
	 *
	 * @return Integer
	 */
	public Integer getCode() {
		return code;
	}
	
	/**
	 * 设置token
	 *
	 */	
	public void setToken(String token) {
		this.token = token;
	}
	
	/**
	 * 获取token
	 *
	 * @return String
	 */
	public String getToken() {
		return token;
	}
	
	/**
	 * 设置userId
	 *
	 */	
	public void setUserId(String userId) {
		this.userId = userId;
	}
	
	/**
	 * 获取userId
	 *
	 * @return String
	 */
	public String getUserId() {
		return userId;
	}
	
	/**
	 * 设置errorMessage
	 *
	 */	
	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}
	
	/**
	 * 获取errorMessage
	 *
	 * @return String
	 */
	public String getErrorMessage() {
		return errorMessage;
	}
	
	@Override
	public String toString() {
		return GsonUtil.toJson(this, TokenResult.class);
	}
}

public class User {

	private static final String UTF8 = "UTF-8";
	private String appKey;
	private String appSecret;
	
	public User(String appKey, String appSecret) {
		this.appKey = appKey;
		this.appSecret = appSecret;

	}
	
	
	/**
	 * 获取 Token 方法 
	 * 
	 * @param  userId:用户 Id,最大长度 64 字节.是用户在 App 中的唯一标识码,必须保证在同一个 App 内不重复,重复的用户 Id 将被当作是同一用户。(必传)
	 * @param  name:用户名称,最大长度 128 字节.用来在 Push 推送时显示用户的名称.用户名称,最大长度 128 字节.用来在 Push 推送时显示用户的名称。(必传)
	 * @param  portraitUri:用户头像 URI,最大长度 1024 字节.用来在 Push 推送时显示用户的头像。(必传)
	 *
	 * @return TokenResult
	 **/
	public TokenResult getToken(String userId, String name, String portraitUri) throws Exception {
		if (userId == null) {
			throw new IllegalArgumentException("Paramer 'userId' is required");
		}
		
		if (name == null) {
			throw new IllegalArgumentException("Paramer 'name' is required");
		}
		
		if (portraitUri == null) {
			throw new IllegalArgumentException("Paramer 'portraitUri' is required");
		}
		
	    StringBuilder sb = new StringBuilder();
	    sb.append("&userId=").append(URLEncoder.encode(userId.toString(), UTF8));
	    sb.append("&name=").append(URLEncoder.encode(name.toString(), UTF8));
	    sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri.toString(), UTF8));
		String body = sb.toString();
	   	if (body.indexOf("&") == 0) {
	   		body = body.substring(1, body.length());
	   	}
	   	
		HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(HostType.API, appKey, appSecret, "/user/getToken.json", "application/x-www-form-urlencoded");
		HttpUtil.setBodyParameter(body, conn);
	    
	    return (TokenResult) GsonUtil.fromJson(HttpUtil.returnResult(conn), TokenResult.class);
	}

}
创建好类之后,在写一个测试类 ,
 
@Service
public class Rongyun {
    /**
     * 审核
     */
    @Transactional
    public HttpResponseEntity adopt() throws Exception {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
                //通过审核
                //注册融云
                String appKey = "替换成您的appkey";//替换成您的appkey
                String appSecret = "替换成匹配上面key的secret";//替换成匹配上面key的secret
//                Reader reader = null ;
                RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
//                                                                              用户名(必填),名字(必填),头像
                    TokenResult userGetTokenResult = rongCloud.user.getToken("2222","张二","");
                 httpResponseEntity.setData(userGetTokenResult);

        return httpResponseEntity;
    }
}
在通过controller 调用,

@RestController
public class RongYunController {

    @Autowired
    private Rongyun rongyun;
    @ResponseBody
    @RequestMapping(value = "/selectByIdrole", method = RequestMethod.POST, headers = "Accept=application/json", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResponseEntity selectByIdrole() throws Exception {
        return rongyun.adopt();
    }
}

在测试一下,
就会得到 用户id为2222的 唯一token(唯一的标识 ,一人一个),也可以去融云官网上查看,是否已经注册成功(通过token,查找用户信息)



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值