com.aliyuncs.http.ProtocolType Java Examples

The following examples show how to use com.aliyuncs.http.ProtocolType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PushUtil.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 推送消息给iOS
 *
 * @param deviceIds
 * @param titale
 * @param body
 * @throws Exception
 */
public static void pushMessageToIOS(String deviceIds, String titale, String body) throws Exception {
    PushMessageToiOSRequest iOSRequest = new PushMessageToiOSRequest();
    //安全性比较高的内容建议使用HTTPS
    iOSRequest.setProtocol(ProtocolType.HTTPS);
    //内容较大的请求,使用POST请求
    iOSRequest.setMethod(MethodType.POST);
    iOSRequest.setAppKey(BaseConfig.iosAppKey);
    iOSRequest.setTarget("DEVICE");
    iOSRequest.setTargetValue(deviceIds);
    iOSRequest.setTitle(titale);
    iOSRequest.setBody(body);
    PushMessageToiOSResponse pushMessageToiOSResponse = BaseConfig.client.getAcsResponse(iOSRequest);
    System.out.printf("RequestId: %s, MessageId: %s\n",
            pushMessageToiOSResponse.getRequestId(), pushMessageToiOSResponse.getMessageId());
}
 
Example #2
Source File: PushUtil.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 推送通知给iOS
 *
 * @param deviceIds
 * @param titale
 * @param body
 * @param parameters
 * @throws Exception
 */
public static void pushNoticeToIOS(String deviceIds, String titale, String body, Object parameters) throws Exception {
    PushNoticeToiOSRequest iOSRequest = new PushNoticeToiOSRequest();
    //安全性比较高的内容建议使用HTTPS
    iOSRequest.setProtocol(ProtocolType.HTTPS);
    //内容较大的请求,使用POST请求
    iOSRequest.setMethod(MethodType.POST);
    iOSRequest.setAppKey(BaseConfig.iosAppKey);
    // iOS的通知是通过APNS中心来发送的,需要填写对应的环境信息. DEV :表示开发环境, PRODUCT: 表示生产环境
    iOSRequest.setApnsEnv("DEV");
    iOSRequest.setTarget("DEVICE");
    iOSRequest.setTargetValue(deviceIds);
    iOSRequest.setTitle(titale);
    iOSRequest.setBody(body);
    iOSRequest.setExtParameters(JSON.toJSONString(parameters));
    PushNoticeToiOSResponse pushNoticeToiOSResponse = BaseConfig.client.getAcsResponse(iOSRequest);
    System.out.printf("RequestId: %s, MessageId: %s\n",
            pushNoticeToiOSResponse.getRequestId(), pushNoticeToiOSResponse.getMessageId());
}
 
Example #3
Source File: OSSUtil.java    From xnx3 with Apache License 2.0 6 votes vote down vote up
static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret,String roleArn, String roleSessionName, String policy,ProtocolType protocolType) throws ClientException {
	try {
		// 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
		IClientProfile profile = DefaultProfile.getProfile(region_cn_hangzhou, accessKeyId, accessKeySecret);
		DefaultAcsClient client = new DefaultAcsClient(profile);
		// 创建一个 AssumeRoleRequest 并设置请求参数
		final AssumeRoleRequest request = new AssumeRoleRequest();
		request.setVersion(sta_api_version);
		request.setMethod(MethodType.POST);
		request.setProtocol(protocolType);
		request.setRoleArn(roleArn);
		request.setRoleSessionName(roleSessionName);
		request.setPolicy(policy);
		// 发起请求,并得到response
		final AssumeRoleResponse response = client.getAcsResponse(request);
		return response;
	} catch (ClientException e) {
		throw e;
	}
}
 
Example #4
Source File: STSServiceImpl.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> getTempAccessPerm(String id) {
    ProtocolType protocolType = ProtocolType.HTTPS;
    try {
        final AssumeRoleResponse response = assumeRole(id, _config.getConf(id, K_roleArn), _config.getConf(id, K_roleSessionName),
                _config.getConf(id, K_policy), protocolType);

        Map<String, String> rsp = new HashMap<String, String>(3, 1);
        rsp.put(K_accessKeyId, response.getCredentials().getAccessKeyId());
        rsp.put(K_accessKeySecret, response.getCredentials().getAccessKeySecret());
        rsp.put(K_securityToken, response.getCredentials().getSecurityToken());
        return rsp;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

    return Collections.emptyMap();
}
 
Example #5
Source File: STSServiceImpl.java    From jframe with Apache License 2.0 6 votes vote down vote up
AssumeRoleResponse assumeRole(String id, String roleArn, String roleSessionName, String policy, ProtocolType protocolType)
        throws ServerException, com.aliyuncs.exceptions.ClientException {
    DefaultAcsClient client = clients.get(id);

    // 创建一个 AssumeRoleRequest 并设置请求参数
    final AssumeRoleRequest request = new AssumeRoleRequest();
    request.setVersion(_config.getConf(id, K_api_version));
    request.setMethod(MethodType.POST);
    request.setProtocol(protocolType);

    request.setRoleArn(roleArn);
    request.setRoleSessionName(roleSessionName);
    request.setPolicy(policy);

    request.setDurationSeconds(Long.parseLong(_config.getConf(id, K_durationSeconds, "3600"))); // 默认值为3600

    // 发起请求,并得到response
    final AssumeRoleResponse response = client.getAcsResponse(request);
    // client.shutdown();

    return response;
}
 
Example #6
Source File: StsServiceSample.java    From jframe with Apache License 2.0 6 votes vote down vote up
static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn, String roleSessionName, String policy,
                                     ProtocolType protocolType) throws ClientException {
    try {
        // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
        IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        // 创建一个 AssumeRoleRequest 并设置请求参数
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(STS_API_VERSION);
        request.setMethod(MethodType.POST);
        request.setProtocol(protocolType);

        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);

        // 发起请求,并得到response
        final AssumeRoleResponse response = client.getAcsResponse(request);

        return response;
    } catch (ClientException e) {
        throw e;
    }
}
 
Example #7
Source File: NoticeService.java    From ticket with GNU General Public License v3.0 5 votes vote down vote up
public void send(NoticeModel noticeModel) {

        try {
            Gson gson = new Gson();
            Map<String, String> map = new HashMap<>();
            map.put("name", noticeModel.getName());
            map.put("username", noticeModel.getUserName());
            map.put("password", noticeModel.getPassword());
            map.put("orderId", noticeModel.getOrderId());

            DefaultProfile profile = DefaultProfile.getProfile("default", noticeConfig.getAccessKeyId(), noticeConfig.getAccessSecret());
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setProtocol(ProtocolType.HTTPS);
            request.setMethod(MethodType.GET);
            request.setDomain(apiConfig.getNotice());
            request.setVersion("2017-05-25");
            request.setAction("SendSms");
            request.putQueryParameter("PhoneNumbers", noticeModel.getPhoneNumber());
            request.putQueryParameter("SignName", noticeConfig.getSignName());
            request.putQueryParameter("TemplateCode", noticeConfig.getTemplateCode());
            request.putQueryParameter("TemplateParam", gson.toJson(map));
            CommonResponse response = client.getCommonResponse(request);
            map = gson.fromJson(response.getData(), Map.class);
            if (map.get("Code").equals("OK")) {
                log.debug("短信通知通知完成{}!", noticeModel.getPhoneNumber());
            } else {
                log.error("短信通知失败:" + map);
            }
        } catch (Exception e) {
            log.error("短信通知失败:" + noticeModel, e);
        }

    }
 
Example #8
Source File: PushUtil.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 推送消息给android
 *
 * @param deviceIds
 * @param titale
 * @param body
 * @throws Exception
 */
public static void pushMessageToAndroid(String deviceIds, String titale, String body) throws Exception {

    PushMessageToAndroidRequest androidRequest = new PushMessageToAndroidRequest();
    /**
     * 安全性比较高的内容建议使用HTTPS
     */
    androidRequest.setProtocol(ProtocolType.HTTPS);
    /**
     * 内容较大的请求,使用POST请求
     */
    androidRequest.setMethod(MethodType.POST);
    androidRequest.setAppKey(BaseConfig.androidAppKey);
    /**
     * 推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
     */
    androidRequest.setTarget("DEVICE");
    /**
     * 根据Target来设定,如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
     */
    androidRequest.setTargetValue(deviceIds);
    androidRequest.setTitle(titale);
    androidRequest.setBody(body);
    PushMessageToAndroidResponse pushMessageToAndroidResponse = BaseConfig.client.getAcsResponse(androidRequest);
    System.out.printf("RequestId: %s, MessageId: %s\n",
            pushMessageToAndroidResponse.getRequestId(), pushMessageToAndroidResponse.getMessageId());

}
 
Example #9
Source File: PushUtil.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 推送通知给android
 *
 * @param deviceIds
 * @param titale
 * @param body
 * @param parameters json数据
 * @throws Exception
 */
public static void pushNoticeToAndroid(String deviceIds, String titale, String body, Object parameters) throws Exception {
    PushRequest pushRequest = new PushRequest();
    //安全性比较高的内容建议使用HTTPS
    pushRequest.setProtocol(ProtocolType.HTTPS);
    //内容较大的请求,使用POST请求
    pushRequest.setMethod(MethodType.POST);
    // 推送目标
    pushRequest.setAppKey(BaseConfig.androidAppKey);
    pushRequest.setTarget("DEVICE");
    //推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
    pushRequest.setTargetValue(deviceIds);
    //根据Target来设定,如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
    pushRequest.setAndroidExtParameters(JSON.toJSONString(parameters));
    pushRequest.setPushType("NOTICE");
    // 消息类型 MESSAGE NOTICE
    pushRequest.setDeviceType("ANDROID");
    // 设备类型 ANDROID iOS ALL.

    // 推送配置
    pushRequest.setTitle(titale); // 消息的标题
    pushRequest.setBody(body); // 消息的内容
    pushRequest.setAndroidNotificationChannel("1");
    // 推送配置: Android
    pushRequest.setAndroidNotifyType("NONE");
    //通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音

    pushRequest.setAndroidRemind(true);

    String expireTime = ParameterHelper.getISO8601Time(new Date(System.currentTimeMillis() + 72 * 3600 * 1000));
    // 12小时后消息失效, 不会再发送
    pushRequest.setExpireTime(expireTime);
    pushRequest.setStoreOffline(true);
    // 离线消息是否保存,若保存, 在推送时候,用户即使不在线,下一次上线则会收到

    PushResponse pushResponse = BaseConfig.client.getAcsResponse(pushRequest);
    System.out.printf("RequestId: %s, MessageID: %s\n",
            pushResponse.getRequestId(), pushResponse.getMessageId());
}
 
Example #10
Source File: FunctionComputeClientTest.java    From fc-java-sdk with MIT License 5 votes vote down vote up
private Credentials getAssumeRoleCredentials(String policy)
    throws com.aliyuncs.exceptions.ClientException {
    IClientProfile profile = DefaultProfile
        .getProfile(REGION, ACCESS_KEY, SECRET_KEY);
    //DefaultProfile.addEndpoint("sts.us-west-1.aliyuncs.com", "us-west-1", "Sts", "sts.us-west-1.aliyuncs.com");
    DefaultAcsClient client = new DefaultAcsClient(profile);

    AssumeRoleRequest request = new AssumeRoleRequest();
    request.setVersion(STS_API_VERSION);
    request.setMethod(MethodType.POST);
    request.setProtocol(ProtocolType.HTTPS);
    request.setRoleArn(STS_ROLE);
    request.setRoleSessionName("test-session");
    if (policy != null) {
        request.setPolicy(policy);
    }

    AssumeRoleResponse stsResponse;
    try {
        stsResponse = client.getAcsResponse(request);
    } catch (com.aliyuncs.exceptions.ClientException e) {
        throw new RuntimeException(e);
    }

    String accessKey = stsResponse.getCredentials().getAccessKeyId();
    String secretKey = stsResponse.getCredentials().getAccessKeySecret();
    String stsToken = stsResponse.getCredentials().getSecurityToken();

    assertNotNull(accessKey);
    assertNotNull(secretKey);
    assertNotNull(stsToken);

    return stsResponse.getCredentials();
}
 
Example #11
Source File: OSSUtil.java    From xnx3 with Apache License 2.0 4 votes vote down vote up
/**
	 * STS 授权给第三方上传,获得临时访问凭证
	 * @param roleSessionName 临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
	 * 							<br/>注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
	 * 							<br/>具体规则请参考API文档中的格式要求
	 * 							<br/>如:alice-001
	 * @param policy RAM和STS授权策略,详细参考 <a href="https://help.aliyun.com/document_detail/31867.html">https://help.aliyun.com/document_detail/31867.html</a>
	 * 			<pre>
	 * 				{
	 * 					"Version": "1",
	 * 					"Statement": [
	 * 						{
	 * 							"Action": [
	 * 								"oss:PutObject", 
	 * 								"oss:GetObject"
	 * 							], 
	 * 							"Resource": [
	 * 								"acs:oss:*:*:*"
	 * 							], 
	 * 							"Effect": "Allow",
	 * 							"Condition": {
	 * 								"IpAddress": {
	 * 									"acs:SourceIp": "192.168.0.*"	//指定ip网段,支持*通配
	 * 								}
	 * 							}
	 * 						}
	 * 					]
	 * 				}
	 * 			</pre>
	 * @return 成功,返回 {@link Credentials} ,失败返回null
	 */
	public static Credentials createSTS(String roleSessionName,String policy){
		String accessKeyId = OSSUtil.accessKeyId;
	    String accessKeySecret = OSSUtil.accessKeySecret;
	    // AssumeRole API 请求参数: RoleArn, RoleSessionName, Policy, and DurationSeconds
	    // RoleArn 需要在 RAM 控制台上获取
//	    String roleArn = "acs:ram::1080155601964967:role/aliyunosstokengeneratorrole";
	    // RoleSessionName 是临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
	    // 但是注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
	    // 具体规则请参考API文档中的格式要求
//		String roleSessionName = "alice-001";
	    // 如何定制你的policy?
//		    String policy = "{\n" +
//		            "    \"Version\": \"1\", \n" +
//		            "    \"Statement\": [\n" +
//		            "        {\n" +
//		            "            \"Action\": [\n" +
//		            "                \"oss:GetBucket\", \n" +
//		            "                \"oss:GetObject\" \n" +
//		            "            ], \n" +
//		            "            \"Resource\": [\n" +
//		            "                \"acs:oss:*:*:*\"\n" +
//		            "            ], \n" +
//		            "            \"Effect\": \"Allow\"\n" +
//		            "        }\n" +
//		            "    ]\n" +
//		            "}";
	    // 此处必须为 HTTPS
	    ProtocolType protocolType = ProtocolType.HTTPS;
	    try {
	    	AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,roleArn, roleSessionName, policy, protocolType);
	    	Credentials credentials = response.getCredentials();
	    	return credentials;
	    } catch (ClientException e) {
	    	e.printStackTrace();
	    	System.out.println("Failed to get a token.");
	    	System.out.println("Error code: " + e.getErrCode());
	    	System.out.println("Error message: " + e.getErrMsg());
	    }
	    return null;
	}
 
Example #12
Source File: StsServiceSample.java    From jframe with Apache License 2.0 4 votes vote down vote up
@Test
public void tokenTest() {
    // 只有 RAM用户(子账号)才能调用 AssumeRole 接口
    // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
    // 请首先在RAM控制台创建一个RAM用户,并为这个用户创建AccessKeys
    String accessKeyId = "";
    String accessKeySecret = "";

    // AssumeRole API 请求参数: RoleArn, RoleSessionName, Polciy, and
    // DurationSeconds

    // RoleArn 需要在 RAM 控制台上获取
    String roleArn = "";

    // RoleSessionName 是临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
    // 但是注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
    // 具体规则请参考API文档中的格式要求
    String roleSessionName = "oss-app-client";

    // 如何定制你的policy?
    // String policy = "{\"Statement\": [{\"Action\": \"oss:*\", "
    // + "\"Effect\": \"Allow\",\"Resource\": \"*\"}],\"Version\": \"1\"}";
    String policy = "{" + " \"Statement\": [ " + "             { " + "                \"Action\": \"oss:*\", "
            + "                 \"Effect\": \"Allow\", " + "                \"Resource\": \"*\" " + "            } " + "          ], "
            + "        \"Version\": \"1\" " + "     } ";

    // String policy = "{\"Statement\": [{\"Action\": \"sts:AssumeRole\","
    // + "\"Effect\": \"Allow\",\"Principal\":{\"Service\":
    // [\"oas.aliyuncs.com\"]}}],\"Version\": \"1\"}";
    // 此处必须为 HTTPS
    ProtocolType protocolType = ProtocolType.HTTPS;

    try {
        final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy, protocolType);

        System.out.println("Expiration: " + response.getCredentials().getExpiration());
        System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
        System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
        System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
    } catch (

            ClientException e) {
        System.out.println("Failed to get a token.");
        System.out.println("Error code: " + e.getErrCode());
        System.out.println("Error message: " + e.getErrMsg());
    }

}