get 方法实例:
String url="http://202.194.14.215/iactivity/mobile/msg.php?act=1";
String tixingfanhuizhi=null;
DefaultHttpClient client=new DefaultHttpClient();//新建client
HttpGet get=new HttpGet(url); //新建httpget
HttpResponse response=null;
get.setHeader("Cookie",getCookie());//setcookie,有的时候可能用不到
response=client.execute(get);
tixingfanhuizhi = EntityUtils.toString(response.getEntity(), "UTF-8");
Document doc=Jsoup.parse(tixingfanhuizhi);//将string返回值生成document文件,然后就可以用Jsoup解析Html文件了
Elements pinglun=doc.select("div");
int a=pinglun.size();
post方法实例
DefaultHttpClient httpclient = new DefaultHttpClient();//创建httpclient
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", username));
params.add(new BasicNameValuePair("key", key));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params, "UTF-8");
HttpPost httppost = new HttpPost(url);
httppost.setEntity(entity); //用post方法,里面放置参数
try {
response = httpclient.execute(httppost);//获得httpresponse
Header header = response.getFirstHeader("Set-Cookie");
if (header != null) {
httpcookie = header.getValue();
}
try {
fanhuishuzhi = EntityUtils.toString(response.getEntity(),
HTTP.UTF_8); //获得其中的内容
code = Integer.parseInt(fanhuishuzhi);//转换为数据值
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),getResources()
.getString(R.string.login_no), Toast.LENGTH_SHORT).show();
dialog.dismiss();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),getResources()
.getString(R.string.login_no), Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),getResources()
.getString(R.string.login_no), Toast.LENGTH_SHORT).show();
dialog.dismiss();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}