packagemain;
importjava.io.IOException;
importjava.io.UnsupportedEncodingException;
importjava.net.URI;
importjava.net.URISyntaxException;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.NameValuePair;
importorg.apache.http.ParseException;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
publicclassMain{
privatestaticHttpClienthc=newDefaultHttpClient();
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
List<NameValuePair>params=newArrayList<NameValuePair>();
params.add(newBasicNameValuePair("email","[email protected]"));
params.add(newBasicNameValuePair("pwd","xxx"));
params.add(newBasicNameValuePair("save_login","1"));
Stringurl="http://www.oschina.net/action/user/login";
Stringbody=post(url,params);
System.out.println(body);
}
/**
*Get请求
*@paramurl
*@paramparams
*@return
*/
publicstaticStringget(Stringurl,List<NameValuePair>params){
Stringbody=null;
try{
//Get请求
HttpGethttpget=newHttpGet(url);
//设置参数
Stringstr=EntityUtils.toString(newUrlEncodedFormEntity(params));
httpget.setURI(newURI(httpget.getURI().toString()+"?"+str));
//发送请求
HttpResponsehttpresponse=hc.execute(httpget);
//获取返回数据
HttpEntityentity=httpresponse.getEntity();
body=EntityUtils.toString(entity);
if(entity!=null){
entity.consumeContent();
}
}catch(ParseExceptione){
e.printStackTrace();
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(URISyntaxExceptione){
e.printStackTrace();
}
returnbody;
}
/**
*//Post请求
*@paramurl
*@paramparams
*@return
*/
publicstaticStringpost(Stringurl,List<NameValuePair>params){
Stringbody=null;
try{
//Post请求
HttpPosthttppost=newHttpPost(url);
//设置参数
httppost.setEntity(newUrlEncodedFormEntity(params));
//发送请求
HttpResponsehttpresponse=hc.execute(httppost);
//获取返回数据
HttpEntityentity=httpresponse.getEntity();
body=EntityUtils.toString(entity);
if(entity!=null){
entity.consumeContent();
}
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnbody;
}
}