使用HashMap对象传递url參数有用工具类

代码例如以下:

package com.yanek.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set; public class HttpUtil { /**
* @param args
*/
public static void main(String[] args) { Map<String, String> paramValues = new HashMap<String, String>();
paramValues.put("b", "2");
paramValues.put("a", "1");
paramValues.put("c","3");
paramValues.put("d","4");
paramValues.put("e","5");
System.out.println("post params::::"+getParams("post",paramValues));
System.out.println("get params::::"+getParams("get",paramValues));
System.out.println("post params::::"+getParamsOrderByKey("post",paramValues));
System.out.println("get params::::"+getParamsOrderByKey("get",paramValues)); }
/**
* 得到參数列表字符串
* @param method 请求类型 get or post
* @param paramValues 參数map对象
* @return 參数列表字符串
*/
public static String getParams(String method,Map<String, String> paramValues)
{
String params="";
Set<String> key = paramValues.keySet();
String beginLetter="";
if (method.equalsIgnoreCase("get"))
{
beginLetter="? ";
} for (Iterator<String> it = key.iterator(); it.hasNext();) {
String s = (String) it.next();
if (params.equals(""))
{
params += beginLetter + s + "=" + paramValues.get(s);
}
else
{
params += "&" + s + "=" + paramValues.get(s);
}
}
return params;
} /**
* 依照key排序得到參数列表字符串
* @param method 请求类型 get or post
* @param paramValues 參数map对象
* @return 參数列表字符串
*/
public static String getParamsOrderByKey(String method,Map<String, String> paramValues)
{
String params="";
Set<String> key = paramValues.keySet();
String beginLetter="";
if (method.equalsIgnoreCase("get"))
{
beginLetter="?";
}
List<String> paramNames = new ArrayList<String>(paramValues.size());
paramNames.addAll(paramValues.keySet());
Collections.sort(paramNames);
for (String paramName : paramNames) { if (params.equals(""))
{
params += beginLetter + paramName + "=" + paramValues.get(paramName);
}
else
{
params += "&" + paramName + "=" + paramValues.get(paramName);
}
} return params;
} }

输出例如以下:

post params::::d=4&e=5&b=2&c=3&a=1
get params::::?d=4&e=5&b=2&c=3&a=1
post params::::a=1&b=2&c=3&d=4&e=5
get params::::?a=1&b=2&c=3&d=4&e=5
上一篇:完全卸载mysql 停止服务、卸载相关程序、删除注册表


下一篇:函数malloc的实现源代码