HttpPost和HttpGet解析

//GET的请求方式
public void httpGet(String name){
// HttpClient得到HttpClient对象
HttpClient httpClient=new DefaultHttpClient();
// 以get方式请求.并设置接口地址
HttpGet httpGet=new HttpGet(path+"ConsName="+name+"&type=year&key=3ac9f31ff66b9746539472887b3799c3");

try {
// 连接网络请求数据,请求到的数据在httpResponse对象里
HttpResponse httpResponse = httpClient.execute(httpGet);
// 服务器返回的内容在HttpEntity
HttpEntity httpEntity = httpResponse.getEntity();
// 把entity转成String
String string = EntityUtils.toString(httpEntity);

System.out.println(string);
Gson gson=new Gson();
Bean bean = gson.fromJson(string, Bean.class);

Message msg=Message.obtain();
msg.obj=bean;
handler.sendMessage(msg);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}





//POST的请求方式
public void httpPost(String name){

HttpClient httpClient=new DefaultHttpClient();
//通过post请求方式
HttpPost httpPost=new HttpPost(path);
//得到一个集合,这个集合是要给服务器传递是数据
List<NameValuePair> list=new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("consName", name));
list.add(new BasicNameValuePair("type", "year"));
list.add(new BasicNameValuePair("key", key));


try {
//设置实体内容和编码格式
UrlEncodedFormEntity urlEncodedFormEntity=new UrlEncodedFormEntity(list, "UTF-8");

//设置实体,用于传递给服务器参数
httpPost.setEntity(urlEncodedFormEntity);

//请求网络
HttpResponse httpResponse=httpClient.execute(httpPost);

//先得到状态行,再得到状态码
if(httpResponse.getStatusLine().getStatusCode()==200){
//得到实体
HttpEntity entity = httpResponse.getEntity();

//得到json数据
String string = EntityUtils.toString(entity);
System.out.println(string);
Gson gson=new Gson();
Bean bean = gson.fromJson(string, Bean.class);

Message msg=Message.obtain();
msg.obj=bean;
handler.sendMessage(msg);
}

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值