一、调用 web 服务获取号码归属地:
1、设置布局:
<?xml version="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:onClick="query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
2、业务代码:
public classDemoActivity extends Activity {
private EditText et_number;
@Override
public void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et_number = (EditText)this.findViewById(R.id.editText1);
}
public void query(View view){
Stringnumber = et_number.getText().toString().trim();
//web中的能获取号码归属地资源的地址
Stringpath =
"http://api.showji.com/Locating/20120413.aspx?m="+number+"&output=json";
try {
//请求地址
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
if(conn.getResponseCode()==200){
//
InputStream is = conn.getInputStream();
//获取json格式的数据
String json = (new String(StreamTools.getBytes(is),"utf-8"));
JSONObject obj = new JSONObject(json);
System.out.println(json);
String text = (String) obj.get("City");
Toast.makeText(this,"归属地为 "+text, 0).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}