首先一个工具类

packagecom.luo.utils;importjava.io.IOException;importjava.io.InputStream;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.Set;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.NameValuePair;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.client.params.HttpClientParams;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.params.BasicHttpParams;importorg.apache.http.params.HttpConnectionParams;importorg.apache.http.params.HttpParams;importorg.apache.http.params.HttpProtocolParams;importorg.apache.http.protocol.HTTP;importorg.apache.http.util.EntityUtils;importandroid.content.Context;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.net.ConnectivityManager;importandroid.net.http.AndroidHttpClient;importandroid.util.Log;importandroid.widget.Toast;/**网络连接*@authorcnmobi-db**/publicclassMyConnect{privatestaticHttpParamshttpParams;privatestaticHttpClienthttpClient;/**get方式请求*@paramurl*@paramparams*@return*/publicstaticStringdoGet(Stringurl,Map<String,String>params){/*建立HTTPGet对象*/StringparamStr="";Set<Map.Entry<String,String>>set=params.entrySet();for(Iterator<Map.Entry<String,String>>it=set.iterator();it.hasNext();){Map.Entry<String,String>entry=(Map.Entry<String,String>)it.next();System.out.println(entry.getKey()+"--->"+entry.getValue());paramStr+=paramStr="&"+entry.getKey()+"="+entry.getValue();}if(!paramStr.equals("")){paramStr=paramStr.replaceFirst("&","?");url+=paramStr;}Log.d("strResult",url);HttpGethttpRequest=newHttpGet(url);StringstrResult="doGetError";try{/*发送请求并等待响应*/HttpResponsehttpResponse=httpClient.execute(httpRequest);/*若状态码为200ok*/if(httpResponse.getStatusLine().getStatusCode()==200){/*读返回数据*/strResult=EntityUtils.toString(httpResponse.getEntity());}else{//strResult="ErrorResponse:"//+httpResponse.getStatusLine().toString();strResult="404";}}catch(ClientProtocolExceptione){//strResult=e.getMessage().toString();strResult="404";e.printStackTrace();}catch(IOExceptione){//strResult=e.getMessage().toString();strResult="404";e.printStackTrace();}catch(Exceptione){//strResult=e.getMessage().toString();strResult="404";e.printStackTrace();}Log.d("strResult",strResult);returnstrResult;}/**post方式请求*@paramsession*@paramurl*@paramparams*@return*/publicstaticStringdoPost(Stringsession,Stringurl,List<NameValuePair>params){Stringwww=url+"?";for(inti=0;i<params.size();i++){if(i!=params.size()-1)www=www+params.get(i).toString()+"&";elsewww=www+params.get(i).toString();}Log.d("strResult","url--->"+www);/*建立HTTPPost对象*/HttpPosthttpRequest=newHttpPost(url);StringstrResult="doPostError";try{/*添加请求参数到请求对象*/httpRequest.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));if(session!=null){httpRequest.setHeader("Cookie",session);System.out.println(session);}/*发送请求并等待响应*/HttpResponsehttpResponse=httpClient.execute(httpRequest);/*若状态码为200ok*/if(httpResponse.getStatusLine().getStatusCode()==200){/*读返回数据*/strResult=EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8);}else{strResult="404";//"ErrorResponse:"+//httpResponse.getStatusLine().toString();}}catch(UnsupportedEncodingExceptione){strResult="404";//e.getMessage().toString();e.printStackTrace();}catch(ClientProtocolExceptione){strResult="404";//e.getMessage().toString();e.printStackTrace();}catch(IOExceptione){strResult="404";//e.getMessage().toString();e.printStackTrace();}catch(Exceptione){strResult="404";//e.getMessage().toString();e.printStackTrace();}Log.d("strResult",strResult);try{strResult=URLDecoder.decode(strResult,HTTP.UTF_8);}catch(UnsupportedEncodingExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}Log.d("strResult",strResult);returnstrResult;}/**配置httpclient*@return*/publicstaticHttpClientgetHttpClient(){//创建HttpParams以用来设置HTTP参数(这一部分不是必需的)httpParams=newBasicHttpParams();//设置连接超时和Socket超时,以及Socket缓存大小HttpConnectionParams.setConnectionTimeout(httpParams,20*1000);HttpConnectionParams.setSoTimeout(httpParams,20*1000);HttpConnectionParams.setSocketBufferSize(httpParams,8192);//设置重定向,缺省为trueHttpClientParams.setRedirecting(httpParams,true);//设置useragentStringuserAgent="Mozilla/5.0(Windows;U;WindowsNT5.1;zh-CN;rv:1.9.2)Gecko/20100115Firefox/3.6";HttpProtocolParams.setUserAgent(httpParams,userAgent);//创建一个HttpClient实例httpClient=newDefaultHttpClient(httpParams);returnhttpClient;}/**获取网络连通状态*@paramcontext*@return*/publicstaticbooleanNetWorkStatus(Contextcontext){booleannetSataus=false;ConnectivityManagercwjManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);cwjManager.getActiveNetworkInfo();if(cwjManager.getActiveNetworkInfo()!=null){netSataus=cwjManager.getActiveNetworkInfo().isAvailable();}if(!netSataus)Toast.makeText(context,"网络错误!",Toast.LENGTH_SHORT).show();returnnetSataus;}/**获取网络图片*@paramurl*@return*/publicstaticBitmaploadImageFromInternet(Stringurl){Bitmapbitmap=null;HttpClientclient=AndroidHttpClient.newInstance("Android");HttpParamsparams=client.getParams();HttpConnectionParams.setConnectionTimeout(params,3000);HttpConnectionParams.setSocketBufferSize(params,3000);HttpResponseresponse=null;InputStreaminputStream=null;HttpGethttpGet=null;try{httpGet=newHttpGet(url);response=client.execute(httpGet);intstateCode=response.getStatusLine().getStatusCode();if(stateCode!=HttpStatus.SC_OK){returnbitmap;}HttpEntityentity=response.getEntity();if(entity!=null){try{inputStream=entity.getContent();returnbitmap=BitmapFactory.decodeStream(inputStream);}finally{if(inputStream!=null){inputStream.close();}entity.consumeContent();}}}catch(ClientProtocolExceptione){httpGet.abort();e.printStackTrace();}catch(IOExceptione){httpGet.abort();e.printStackTrace();}finally{((AndroidHttpClient)client).close();}returnbitmap;}}


然后创建一个异步任务内部类

classGethispetsAsyncTaskextendsAsyncTask<Object,Object,Object>{ProgressDialogdialog=ProgressDialog.show(HeActivity.this,null,"正在查询宠物信息,请稍后......");privateStringurl;privateStringtoken;privateStringuid;publicGethispetsAsyncTask(Stringurl,Stringtoken,Stringuid){this.url=url;this.token=token;this.uid=uid;}@OverrideprotectedObjectdoInBackground(Object...params){Stringcode="1";MyConnect.getHttpClient();Map<String,String>parms=newLinkedHashMap<String,String>();parms.put("token",token);parms.put("uid",uid);StringjsonContent=MyConnect.doGet(url,parms);try{JSONObjectjsonObject=newJSONObject(jsonContent);if(jsonObject!=null){code=jsonObject.getString("code");if(jsonObject.has("petArray")){Stringj1=jsonObject.getString("petArray");JSONArrayj2=newJSONArray(j1);for(inti=0;i<j2.length();i++){JSONObjectjsonObject2=j2.getJSONObject(i);Stringj3=jsonObject2.getInt("weight")+"KG";Stringj4=jsonObject2.getString("nickname");Stringj5=jsonObject2.getString("birthday");Stringj6=jsonObject2.getString("breed");HashMap<String,String>map=newHashMap<String,String>();map.put("weight",j3);map.put("name",j4);map.put("bir",j5);map.put("kind",j6);hispetList.add(map);}}if(jsonObject.has("terminalArray")){Stringter=jsonObject.getString("terminalArray");JSONArraytermes=newJSONArray(ter);for(inti=0;i<termes.length();i++){JSONObjectjsonObject3=termes.getJSONObject(i);Stringterid=jsonObject3.getString("terminalId");Stringdist=jsonObject3.getString("dist");HashMap<String,String>map1=newHashMap<String,String>();map1.put("terminalId",terid);map1.put("dist",dist);histerList.add(map1);}}}}catch(JSONExceptione){e.printStackTrace();}returncode;}@OverrideprotectedvoidonPostExecute(Objectresult){super.onPostExecute(result);System.out.println("-----result------>"+result);dialog.dismiss();if(result.equals("0")){hispetapter=newSimpleAdapter(HeActivity.this,hispetList,R.layout.list_itemhispet,newString[]{"weight","bir","kind","name"},newint[]{R.id.weight,R.id.bir,R.id.kind,R.id.name});listView.setAdapter(hispetapter);histerapter=newSimpleAdapter(HeActivity.this,histerList,R.layout.list_itemhister,newString[]{"terminalId","dist"},newint[]{R.id.ter,R.id.dist});listView2.setAdapter(histerapter);}elseif(result.equals("40008")){Toast.makeText(HeActivity.this,"身份信息过期,请重新登录",Toast.LENGTH_SHORT).show();}else{}}}


最后启动异步任务

newGethispetsAsyncTask(ConstantUtils.host1+ConstantUtils.url_26,ConstantUtils.token,uid+"").execute(null,null,null);