OAuth2.0 https

本文介绍了一个使用 Java 实现的 Yimall OAuth 认证过程。通过配置 SSL 信任管理器来忽略证书验证,并设置了 HTTPS 连接参数进行 POST 请求,最终获取 access_token。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	/**
	 * OAuth 认证
	 * @throws Exception
	 */
	public String requestYimallOAuth() throws Exception {
		
		TrustManager[] trustAllCerts = new TrustManager[] {
				   new X509TrustManager() {
				      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				        return null;
				      }

				      public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

				      public void checkServerTrusted(X509Certificate[] certs, String authType) {  }

				   }
				};
		
			SSLContext sc;
			sc = SSLContext.getInstance("SSL");
			
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

			// Create all-trusting host name verifier
			HostnameVerifier allHostsValid = new HostnameVerifier() {
			    public boolean verify(String hostname, SSLSession session) {
			      return true;
			    }
			};
			// Install the all-trusting host verifier
			HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
			
			URL url = new URL("");//  你要请求的地址
			HttpsURLConnection httpsURLConnection=(HttpsURLConnection)url.openConnection();
			httpsURLConnection.setConnectTimeout(30000);
			httpsURLConnection.setReadTimeout(30000);
			httpsURLConnection.setDoOutput(true);
			httpsURLConnection.setDoInput(true); 
			httpsURLConnection.setUseCaches(true);   
			httpsURLConnection.setRequestMethod("POST");

			httpsURLConnection.connect();

			int responseCode=httpsURLConnection.getResponseCode();
			InputStream input=null;
			if(responseCode==200){
				input=httpsURLConnection.getInputStream();
			}else{
				input=httpsURLConnection.getErrorStream();
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(input));
			StringBuilder result=new StringBuilder();
			String line=null; 
			while((line=in.readLine())!=null){
				result.append(line);
			}
			
			String access_token = result.toString();
			System.out.println(access_token);
			return "success";
	}

  

转载于:https://www.cnblogs.com/jayGold/p/3487876.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值