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();
}
}