public class HttpClientUtils {
private static final String CHARSET = "UTF-8";
/*
* http get请求
*
* @param url
*
* @param params
*
* @return
*/
public static String httpGet(String url, Map<String, String> params) {
if (true == StringUtils.isEmpty(url)) {
return null;
}
List<NameValuePair> pl = getParamList(params);
// 转换参数
if (null != pl) {
String urlparams = URLEncodedUtils.format(pl, CHARSET);
url = url + "?" + urlparams;
}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
try {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (null != entity) {
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/*
* http post请求
*
* @param url
*
* @param params
*
* @return
*/
public static String httpPost(String url, Map<String, String> params) {
if (true == StringUtils.isEmpty(url)) {
return null;
}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> pl = getParamList(params);
// 转换参数
if (null != pl) {
HttpEntity entity;
try {
entity = new UrlEncodedFormEntity(pl);
httppost.setEntity(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (null != entity) {
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/*
* 创建标准的NameValuePair格式参数
*
* @param params
*
* @return
*/
public static List<NameValuePair> getParamList(Map<String, String> params) {
if (null == params || 0 == params.size()) {
return null;
}
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> param : params.entrySet()) {
list.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
return list;
}
}
public class HttpClientUtilsTest extends TestCase {
private static final String LOG_TAG = "HttpClientUtilsTest";
public void testHttpGet1(){
String url = "http://192.168.1.101:3000/gettest";
String result = HttpClientUtils.httpGet(url, null);
System.out.println(result);
Log.i(LOG_TAG, result);
}
public void testHttpGet2(){
String url = "http://192.168.1.101:3000/gettest";
Map<String,String> map = new HashMap<String,String>();
map.put("username", "fredric");
map.put("password", "fredrictoo");
String result = HttpClientUtils.httpGet(url, map);
System.out.println(result);
Log.i(LOG_TAG, result);
}
public void testHttpPost1(){
String url = "http://192.168.1.101:3000/posttest";
Map<String,String> map = new HashMap<String,String>();
map.put("username", "sinny");
map.put("password", "sinnytoo");
String result = HttpClientUtils.httpPost(url, map);
System.out.println(result);
Log.i(LOG_TAG, result);
}
}