记录一次项目中的单点登录(DES3Util,HttpUtils,HttpTest)

之前写了项目的接口文档(第一次写),然后是手机APP端要用,因为开发手机APP功能,所以要使用到我们的项目系统获取数据,调用我们这边的接口。
然后那边按照我给的 接口文档进行接口调试,第一次出现了"用户尚未登录";有点懵逼。因为我没搞过单点登录,之前只是学习CAS单点登录系统。项目中是第一次遇见。基本大半年也没咋么学习,每天下班也晚。有点忘记了。找我师父,师父给了我例子,就3个java文件(2个工具类,一个测试类)。在下方,具体原理:还不是很清楚。代码如下:

DES3Util.java

package http;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class DES3Util{

		//1:ECB加密,不要Ⅳ :key-密钥(mM2GzKbb4ZI=)   data-明文(密码)   return-Base64编码的密钥
		public static byte[] des3EncodeECB(byte[] key,byte[] data) throws Exception{
			Key deskey = null;
			DESedeKeySpec spec = new DESedeKeySpec (key); //创建密钥spec
			SecretKeyFactory keyFactory = SecretKeyFactory .getInstance("desede");//获取密钥工厂
			deskey = keyFactory.generateSecret(spec);//密钥工厂根据 密钥规格 生成 新密钥
			
			Cipher  cipher = Cipher.getInstance("desede"+"/ECB/PKCS5Padding");//这我就不懂了
			cipher.init(Cipher.ENCRYPT_MODE,deskey); //使用cipher加密-新密钥
			byte[] bout = cipher.doFinal(data); //生成Base64编码的密码
			return bout;
		}

	 //2:ECB解密 不要Ⅳ:key-密钥(),data-Base64编码的密码 return-明文
		public static byte[] des3DecodeECB(byte[] key,byte[] data) throws Exception{
			Key deskey = null;
			DESedeKeySpec spec = new DESedeKeySpec (key); //创建密钥spec
			SecretKeyFactory keyFactory = SecretKeyFactory .getInstance("desede");//获取密钥工厂
			deskey = keyFactory.generateSecret(spec);//密钥工厂根据 密钥规格 生成 新密钥
			
			Cipher  cipher = Cipher.getInstance("desede"+"/ECB/PKCS5Padding");//这我就不懂了
			cipher.init(Cipher.DECRYPT_MODE,deskey); //使用cipher解密-新密钥
			byte[] bout = cipher.doFinal(data); //生成明文
			return bout;

	}

//3:加密--正常用法 --(indata-17656)
	public static String encode(String indata) throws Exception{
		byte[] key = new BASE64Decoder().decodeBuffer("XB5DZaVmHpSUtsAJ1vTH6yE1c1dHd0");
		byte[] data = indata.getBytes("UTF-8");
		byte[] str3 = des3EncodeECB(key,data); //获取用户名加密的字节数组
		String retstr = (new BASE64Encoder().encode(str3));//进行Base64加密
		retstr = retstr.replace("\r\n","");//使用右边的 替换左边的
  		retstr = retstr.replace("\r","");
		retstr = retstr.replace("\n","");
		return  	retstr;
	}
	
//4:测试	
public static void main()throws Exception{
	String encode = encode("17656");
	System.out.println(encode);
}

}

//HttpUtils.java

package http;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity;StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;

impot net.sf.json,JSONObject;


public class HttpUtils{

	private CookieStore cookiStore = null;
	public JSONObject httpPostWithJson()throws Exception{
		HttpPost post = null ;
		try{
			CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			post = new HttpPost(url);
			//构造消息头
			post.setHeader("Content-type","application/json;charset=uft-8");
			post.setHeader("Connection","Close");
			//构造消息实体
			StringEntity entity = new StringEntity(jsonObject.toString(),Charset.forName("UTF-8"));
			entity.setContentEncoding("utf-8");
			//发送Json格式的数据请求
			entity.setContentType("application/json");
			post.setEntity(entity);

			HttpResponse response = httpClient.execute(post);
			String host = post.getURI().getHost();
			setCookieStore(response,host);
			
			//校验返回码
			int statusCode = response.getStatusLine().getStatusCode();
				if( statusCode != HttpStatus.SC_OK ) {
						throw new Exception("请求出错:"+statusCode+":"+repsonse.getStatusLine().getReasonPhrase());
				}else{
					//输出返回内容
					HttpEntity responseEntity = response.getEntity();
						if(repsonseEntity !=  null ){
						InputStream inputStream = responseEntity.getContent();
							try{
									int k; 
									StringBuffer sbf = new StringBuffer();
									byte[] bytes = new Byte[1024];
										while( (k = inputStream.read(bytes)) != -1 ){
										sbf.append(new String (bytes,0,k,"utf-8"));
										}
										return JSONObject.fromObject(sbf.toString());
									}finally{
									inputStream.close();
									}	
						}
				}
				//if else 都没走。
			return null;
			 }finally{
			 	if(post != null){
			 		post.releaseConnection();
			 		}
			 }
	}

//设置cookieStore
	public void setCookieStore(HttpResponse httpResponse, String host)throws Exception{
			if( cookieStore != null )return ;
			if(null != httpResponse.getFirstHeader("Set-Cookie")){
				String setCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
				String JSESSIONID = setCookie.subString("JSESSIONID=".length(),setCookie.indexOf(";")); //包左不包右
				//新建一个Cookie
				BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",JSESSIONID);
				cookie.setVersion(0);
				cookie.setDomain(host);
				cookie.setPath("/");
				cookieStore = new BasicCookieStore();
				cookieStore.addCookie(cookie);  //添加客户端cookie到cookie存储中
				}
	}

}//类尾

//HttpTest

package http;

import net.sf.json.JSONObject;

public class HttpTest{

	public static void main(String[] args)throws Exception{
		HttpUtils httputils = new HttpUtils();
		JSONObject jsonObj = new JSONObject();
		//登录请求
		JSONObject ret = httputils.httpPostWithJson(jsonObj,
		"http://10.1.1.191:8080/xxxxx/sso/slogin.do?userId=17656&userKey="+DES3Util.encode("17656"));
	
		ret = httputils.httpPostWithJson(jsonObi,
		"http://10.1.1.191:8080/xxxxx/queryRoles.do");
		if(!"success".equals(ret.getString("code"))){
				throw new Exception(ret.getString("data"));
		}
		System.out.println(ret);
}

}//类尾

猜你喜欢

转载自blog.csdn.net/little_dream2018/article/details/88943391