junit单元测试工具类

来源:互联网 发布:伊戈达拉身体数据 编辑:程序博客网 时间:2024/05/17 23:47
package org.benpaobang.system.utils;


import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
/**
 * 
* @ClassName: HttpClientUtils 
* @Description: test测试工具类
* @author llj
* @date 2015年12月2日 下午3:36:22 
*
 */
public class HttpClientUtils {
/**
* 默认的编码,解决中文乱码
*/
public static String defaultEncode = "UTF-8";
/**
* 发送Post请求

* @param url
*            请求路径
* @param paramMap
*            参数
* @return 响应体
*/
public static String getSendPost(String url, Map<String, String> paramMap) {
return getSendPost(url, paramMap, defaultEncode);
}

/**
* 发送Post请求

* @param url
*            请求路径
* @param paramMap
*            参数
* @return 响应体
*/
public static String getSendPost(String url, Map<String, String> paramMap, String encode) {
StringBuffer buf = new StringBuffer();
HttpClient client = new HttpClient();       
PostMethod postMethod = new PostMethod(url);
if (paramMap.size() > 0) {
NameValuePair[] params = new NameValuePair[paramMap.size()];
Iterator<Entry<String, String>> it = paramMap.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry<String, String> map = (Map.Entry<String, String>) it.next();
params[i] = new NameValuePair(map.getKey(), map.getValue());
i++;
}
postMethod.setQueryString(params); // post请求参数用setQueryString
}
try {
client.executeMethod(postMethod);
byte[] responseBody = postMethod.getResponseBody();
String content = new String(responseBody, encode);
buf.append(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return buf.toString();
}

/**
* @Title: httpGet
* @Description: HTTP GET 请求

* @param url 请求地址
* @return 请求结果
*/
public static String httpGet(String url){
StringBuffer buf = new StringBuffer();
HttpClient client = new HttpClient(); 
GetMethod getMethod = new GetMethod(url);
try {
client.executeMethod(getMethod);

byte[] responseBody = getMethod.getResponseBody();
String content = new String(responseBody, defaultEncode);
buf.append(content);

} catch (Exception e) {
e.printStackTrace();
} finally {
getMethod.releaseConnection();
}

return buf.toString();
}


}
0 0