java http client参数唯一性校验

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.util.TextUtils;
import org.javahash.hash.HashFactory;


import com.jcabi.http.Request;
import com.jcabi.http.request.JdkRequest;
import com.jcabi.http.response.RestResponse;

/** 
 * java httpclient参数唯一性校验  客户端
 * @author Administrator
 * 用到jcabi-http
 */
public class TestSend {

	private static String API="123123";

	public static void main(String[] args) throws Exception {

		Map<String, String> map=new HashMap<String, String>();
		map.put("username", "admin");
		map.put("passwrod", "123456");
		map.put("data", "我是中国人");
		
		List<Map.Entry<String, String>> list=kSort(map);
		String old=getSort(list);
		System.out.println("old="+old);
		String sign=API+HashFactory.getInstance().getHash("MD5").getHash(old.getBytes("UTF-8"))+API;
		System.out.println("sign="+sign);
		
		map.put("sign", sign);	
		//get 方法使用
		String html = new JdkRequest("http://127.0.0.1:8080/httpserver/index.do").method(Request.GET).uri()
		.queryParams(map)
		.back().fetch().setCharset("UTF-8").as(RestResponse.class)
		.assertStatus(HttpURLConnection.HTTP_OK).body();
		System.out.println(html);
	}

	protected static String getSort(List<Map.Entry<String, String>>  nameValuePairs){
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> nameValuePair : nameValuePairs) {
			if (!TextUtils.isEmpty(nameValuePair.getKey())) {
				sb.append("&").append(nameValuePair.getKey()).append("=").append(nameValuePair.getValue());
			}
		}
		return sb.toString().substring(1);
	}
	
	private static List<Map.Entry<String, String>> kSort(Map<String, String> nameValuePairs) {
		List<Map.Entry<String, String>> list=new ArrayList<Map.Entry<String, String>>(nameValuePairs.entrySet());
		Collections.sort(list,new Comparator<Map.Entry<String, String>>() {

			@Override
			public int compare(Entry<String, String> o1,
					Entry<String, String> o2) {
				
				
				 return (o1.getKey()).compareTo(o2.getKey());
			}
		});
		return list;
	}
}
package com.jiepu;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.javahash.hash.HashFactory;
import org.javahash.hash.exception.UnableToCalculateException;


/**
 *java http参数唯一性校验 服务器端
 * @author Administrator
 */
public class BaseServlet extends HttpServlet {

	private static String API="123123";

	private static final long serialVersionUID = 8791110963130113593L;

	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	System.out.println("doget");
    	doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //
        StringBuffer sb = new StringBuffer();
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        request.getSession().setAttribute("admin", "admin");
        Cookie[] cookies = request.getCookies();
        
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                sb.append("cookie:"+cookie.getName() + "=" + cookie.getValue()+"<br/>");
                cookie.setValue("admin_cookie");
               
            }
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String uri = request.getRequestURI();
        String method = request.getMethod();
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        Map<String, String[]> maps = request.getParameterMap();
        Map<String, String> signMap=new HashMap<String, String>();
       // List<Map.Entry<String, String>> signList=new ArrayList<Map.Entry<String,String>>();
        
        //System.out.println(TypeUtil.typeToString("maps", maps));
        Set<Map.Entry<String, String[]>> entrys = maps.entrySet();
        for (Map.Entry<String, String[]> entry : entrys) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            sb.append(key + "=");
            for (String string : values) {
                sb.append(string + ",");
            }
            //
            if(values.length>0 && !key.equals("sign"))
            {
            	 signMap.put(key, values[0]);
            }
        }
        if(sb.length()>0)
        {
        	sb.append(",");
        }
        sb.append("ip=" + ip + ",uri=" + uri + ",method=" + method);
        
        List<Map.Entry<String, String>> list=Tool.kSort(signMap);
		String old=Tool.getSort(list);
		System.out.println("old="+old);

		String sign="";
		try {
			sign =API+ HashFactory.getInstance().getHash("MD5").getHash(old.getBytes("UTF-8"))+API;
		} catch (UnableToCalculateException e) {
			e.printStackTrace();
		}
		System.out.println("sign="+sign);
		
        String recSign=request.getParameter("sign");
        System.out.println("recSign="+recSign);
        if(recSign!=null)
        {
        	if(sign.equals(recSign))
        	{
        		System.out.println("ok");
        		sb.append(" sign ok ");
        	}else{
        		System.out.println("not ok ");
        		sb.append(" sign not  ok ");
        	}
        }        
        response.getWriter().print(sb.toString());
        System.out.println(sb.toString());
       // super.doPost(request, response);
    }

    @Override
    protected void service(HttpServletRequest hsr, HttpServletResponse hsr1) throws ServletException, IOException {
        super.service(hsr, hsr1);
    }
}

package com.jiepu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class Tool {


	protected static String getSort(List<Map.Entry<String, String>>  nameValuePairs){
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> nameValuePair : nameValuePairs) {
			if (!isEmpty(nameValuePair.getKey())) {
				sb.append("&").append(nameValuePair.getKey()).append("=").append(nameValuePair.getValue());
			}
		}
		return sb.toString().substring(1);
	}
	

    public static boolean isEmpty(final CharSequence s) {
        if (s == null) {
            return true;
        }
        return s.length() == 0;
    }

    public static boolean isBlank(final CharSequence s) {
        if (s == null) {
            return true;
        }
        for (int i = 0; i < s.length(); i++) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }


	static List<Map.Entry<String, String>> kSort(Map<String, String> nameValuePairs) {
		List<Map.Entry<String, String>> list=new ArrayList<Map.Entry<String, String>>(nameValuePairs.entrySet());
		Collections.sort(list,new Comparator<Map.Entry<String, String>>() {

			@Override
			public int compare(Entry<String, String> o1,
					Entry<String, String> o2) {
				
				
				 return (o1.getKey()).compareTo(o2.getKey());
			}
		});
		return list;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值