JAVA Http Basic auth获取token

本文主要参考:https://www.cnblogs.com/xiaocandou/p/7991927.html

应用在获取 token 时,可以向 api 管理平台发起一个 HTTP POST 请求,内容如下:
• 请求地址: https://****.com/token
• 请求内容: grant_type=client_credentials
• 请求 Content-type: application/x-www-form-urlencoded
• 身份验证: Basic Auth,用户名为 Consumer ID,密码为 Consumer Key  
		  @Override
		  public String reFreshToken(ParkBean park) 
		  {
			  String token="";//token有效期为24小时
			  String coscoUrl="https://***.com:8443";
			  String[] split = coscoUrl.split(":");
			//  System.out.println(split[0] +"  " +split[1].substring(2,split[1].length())+" "+split[2]);
			  
					//HttpHost target = new HttpHost("tax.coscoshipping.com", 8443,"https");
			    //分解出域名及端口和https
			       HttpHost target = new HttpHost(split[1].substring(2,split[1].length()), Integer.valueOf(split[2]),split[0]);
			        CredentialsProvider credsProvider = new BasicCredentialsProvider();
			        String user=park.getJrdm();//"LcXLUfRXv49ZZlu99jX7fsHafCAa";
			        String password= park.getKeypwd()  ;//"Pnf269RTrdydqUhqe5nGjGtLj_Ma";
			        credsProvider.setCredentials(
			                new AuthScope(target.getHostName(), target.getPort()),
			                new UsernamePasswordCredentials(user, password));
			        CloseableHttpClient httpclient = HttpClients.custom()
			                .setDefaultCredentialsProvider(credsProvider).build();
			    	try {
			            // Create AuthCache instance
			            AuthCache authCache = new BasicAuthCache();
			            // Generate BASIC scheme object and add it to the local
			            // auth cache
			            BasicScheme basicAuth = new BasicScheme();
			            authCache.put(target, basicAuth);

			            // Add AuthCache to the execution context
			            HttpClientContext localContext = HttpClientContext.create();
			            localContext.setAuthCache(authCache);
			            //https://***.com:8443/api/token 
			            HttpPost httppost = new HttpPost(coscoUrl+"/api/token");
			    		HttpEntity reqEntity = null;
			    		JSONObject  json = new JSONObject();
			    		json.put("grant_type", "client_credentials");
			    		List<NameValuePair>  params =toCharge(json);
			    	
			   
			    			if(null!=params && !params.isEmpty())reqEntity = new UrlEncodedFormEntity(params, "UTF-8");
			    			httppost.setEntity(reqEntity);
			    			System.out.println("Executing request " + httppost.getRequestLine() + " to target " + target);
				           
				                CloseableHttpResponse response = httpclient.execute(target, httppost, localContext);
				                try
					              {
				                	HttpEntity entity = response.getEntity();
				        			if (entity != null) {
				        				String result  = EntityUtils.toString(entity, encoding);
				        				log.debug("***返回值***:"+result);
				        				JSONObject jsonObject = JSONObject.fromObject(result);
				        				//{"access_token":"eef0908c-a167-3148-b9dc-2318ecc6b22c","scope":"am_application_scope default","token_type":"Bearer","expires_in":3600}
				        			 
				        			 } 
					              }
			        			 finally {
			                         response.close();
			                     }

			                }catch(Exception e)
		                    {
			                	log.debug("获取token失败 "+e.getMessage());
		                    }finally {
		                    	if(httpclient!=null)
		                    	{
		                    		try {
										httpclient.close();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
		                    	}
								
								 
			                }
			            
			 
			 	return token;
			 	 
		  }
	  public static 	List<NameValuePair> toCharge( JSONObject params) {
				List<NameValuePair> listParam = new ArrayList<NameValuePair>();
				if(params!=null&&params.size()>0)
				{
				  for(Iterator it  = params.keySet().iterator();it.hasNext();){ ////这个返回key集合的对象  
			          String key = (String) it.next();  
			           if(params.get(key)!=null){
			        	   listParam.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
			           }
			       }
				}
			  return listParam;
				}

  

 
 
posted @ 2023-09-12 11:44  幸福眼泪  阅读(313)  评论(0编辑  收藏  举报