Android手机号码归属地的查询
一个简单的Demo,从聚合数据申请手机号码归属地数据接口;
在EditText中输入待查询号码,获取号码后在子线程中使用HttpUrlconnection获取JSON数据,之后进行解析;
数据获取完成后,在主线程中更新UI,显示获取的号码归属地信息。
布局文件
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/et_querylocation" android:layout_height="wrap_content" android:layout_width="match_parent" android:textColor="#000000" android:hint="输入号码"/> <Button android:onClick="query" android:textSize="24sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查询"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tv_phonelocation" android:textSize="20sp" android:textColor="#000000"/> </LinearLayout>
java代码
packagecom.example.phonehome; importjava.io.BufferedReader; importjava.io.DataOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.UnsupportedEncodingException; importjava.net.HttpURLConnection; importjava.net.URL; importjava.net.URLEncoder; importjava.util.HashMap; importjava.util.Map; importorg.json.JSONObject; importandroid.app.Activity; importandroid.os.Bundle; importandroid.os.Handler; importandroid.text.TextUtils; importandroid.view.View; importandroid.widget.EditText; importandroid.widget.TextView; importandroid.widget.Toast; publicclassMainActivityextendsActivity{ privateEditTextet_phone; privateTextViewtv_phone; privatefinalstaticintSTART=0; privatefinalstaticintFINISH=1; privateStringphone;//待查询号码 //号码信息 privatestaticStringprovince; privatestaticStringcity; privatestaticStringcompany; privatestaticStringcard; publicstaticfinalStringDEF_CHATSET="UTF-8"; publicstaticfinalintDEF_CONN_TIMEOUT=30000; publicstaticfinalintDEF_READ_TIMEOUT=30000; publicstaticfinalStringAPPKEY="申请的APPKEY"; //子线程中查询数据开始、完成时发送消息,完成相应操作 Handlerhandler=newHandler(){ publicvoidhandleMessage(android.os.Messagemsg){ switch(msg.what){ caseSTART: Toast.makeText(MainActivity.this,"正在查询,请稍候",Toast.LENGTH_SHORT).show(); break; caseFINISH: //在Textview中显示查得的号码信息(子线程中不能更新UI) tv_phone.setText(province+""+city+""+company+""+card); break; default: break; } }; }; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); initView(); } //Button的店家事件,获取待查询号码后在子线程中进行查询 publicvoidquery(Viewv){ phone=et_phone.getText().toString().trim(); if(!TextUtils.isEmpty(phone)){ newThread(){ publicvoidrun(){ //开始查询 handler.obtainMessage(START).sendToTarget(); getRequest(phone); //查得结果 handler.obtainMessage(FINISH).sendToTarget(); }; }.start(); }else{ Toast.makeText(MainActivity.this,"输入号码不能为空",Toast.LENGTH_SHORT).show(); } } //手机归属地查询 publicstaticvoidgetRequest(Stringphone){ Stringresult=null; Stringurl="http://apis.juhe.cn/mobile/get";//请求接口地址 Mapparams=newHashMap();//请求参数 params.put("phone",phone);//需要查询的手机号码或手机号码前7位 params.put("key",APPKEY);//应用APPKEY(应用详细页查询) params.put("dtype","");//返回数据的格式,xml或json,默认json try{ //得到JSON数据,并进行解析 result=net(url,params,"GET"); JSONObjectobject=newJSONObject(result); JSONObjectob=newJSONObject(object.get("result").toString()+""); province=ob.getString("province"); city=ob.getString("city"); company=ob.getString("company"); card=ob.getString("card"); }catch(Exceptione){ e.printStackTrace(); } } /** * *@paramstrUrl请求地址 *@paramparams请求参数 *@parammethod请求方法 *@return网络请求字符串 *@throwsException */ publicstaticStringnet(StringstrUrl,Mapparams,Stringmethod)throwsException{ HttpURLConnectionconn=null; BufferedReaderreader=null; Stringrs=null; try{ StringBuffersb=newStringBuffer(); if(method==null||method.equals("GET")){ strUrl=strUrl+"?"+urlencode(params); } URLurl=newURL(strUrl); conn=(HttpURLConnection)url.openConnection(); if(method==null||method.equals("GET")){ conn.setRequestMethod("GET"); }else{ conn.setRequestMethod("POST"); conn.setDoOutput(true); } //conn.setRequestProperty("User-agent",userAgent); conn.setUseCaches(false); conn.setConnectTimeout(DEF_CONN_TIMEOUT); conn.setReadTimeout(DEF_READ_TIMEOUT); conn.setInstanceFollowRedirects(false); conn.connect(); if(params!=null&&method.equals("POST")){ try{ DataOutputStreamout=newDataOutputStream(conn.getOutputStream()); out.writeBytes(urlencode(params)); }catch(Exceptione){ //TODO:handleexception e.printStackTrace(); } } InputStreamis=conn.getInputStream(); reader=newBufferedReader(newInputStreamReader(is,DEF_CHATSET)); StringstrRead=null; while((strRead=reader.readLine())!=null){ sb.append(strRead); } rs=sb.toString(); }catch(IOExceptione){ e.printStackTrace(); }finally{ if(reader!=null){ reader.close(); } if(conn!=null){ conn.disconnect(); } } returnrs; } //将map型转为请求参数型 publicstaticStringurlencode(Map<String,String>data){ StringBuildersb=newStringBuilder(); for(Map.Entryi:data.entrySet()){ try{ sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&"); }catch(UnsupportedEncodingExceptione){ e.printStackTrace(); } } returnsb.toString(); } privatevoidinitView(){ setContentView(R.layout.activity_main); et_phone=(EditText)findViewById(R.id.et_querylocation); tv_phone=(TextView)findViewById(R.id.tv_phonelocation); } }
以上就是本文的全部内容,希望对大家的学习有所帮助。