import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
* http工作类
* @author lisu005
* httpcore-4.2.4.jar
* httpclient-4.2.5.jar
*/
public class HttpUtil {
private DefaultHttpClient client = new DefaultHttpClient();
/**
* 创建get请求
* @param url
* @return
* @throws Exception
*/
public HttpResponse getGet(String url) throws Exception{
try {
HttpGet getMethod = new HttpGet(url);
HttpResponse response = client.execute(getMethod);
return response;
} catch (Exception e) {
throw new Exception("创建get请求异常……", e);
}
}
/**
* 创建post请求方法
* @param url
* @param params
* @return
* @throws Exception
*/
public HttpResponse getPost(String url,Map<String,String> params) throws Exception{
try {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Entry<String,String>> set = params.entrySet();
Iterator<Entry<String,String>> iter = set.iterator();
while(iter.hasNext()){
Entry<String,String> entry = iter.next();
String key = entry.getKey();
String value = entry.getValue();
nvps.add(new BasicNameValuePair(key, value));
}
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(post);
return response;
} catch (UnsupportedEncodingException e) {
throw new Exception("添加post参数异常……", e);
} catch(Exception e){
throw new Exception("创建Post请求异常……", e);
}
}
public static void main(String[] args) throws Exception {
HttpUtil bean= new HttpUtil();
Map<String, String> params = new HashMap<String, String>();
HttpResponse resp = bean.getPost("http://pa18-wcm-stg.paic.com.cn/search/admin/login.do", params);
String entity = EntityUtils.toString(resp.getEntity());
System.out.println(entity);
}
}