Android中的网络请求主要有GET和POST方式。POST方式比GET方式更为安全,因为需要发送的消息不是嵌入在url中的,同时能比GET发送更多的数据。
本文讨论使用POST方式向聚合数据API发送请求,以获得手机号码归属地的信息。归属地查询的接口的请求示例为:http://apis.juhe.cn/mobile/get?phone=13429667914&key=您申请的KEY。默认返回的格式为JSON。最后把返回结果显示在TextView上。直接上代码:
public class MainActivity extends Activity {
private TextView text;
private String url = "http://apis.juhe.cn/mobile/get";//向服务器请求的url.
private Handler handler = new Handler();//使用Handler更新UI,因为网络操作是在子线程中进行的,子线程不能更新UI,所以只能使用Handler机制;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(id_text);
//新建线程Thread,开始网络操作。
new Thread() {
@Override
public void