进行Android应用开发,其中不得不使用到网络编程,最基本的就是向服务器发送Http请求,并接收从服务器返回的数据,该类数据一般为JSON或XML格式。
向服务器进行请求数据一般有GET、POST两种方式,两者基本类似,以GET居多。本文先讨论使用GET方式向聚合数据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?phone=13429667914&key=9719c91bd4ac2647c67c6cd067b5cb8e";//向服务器请求的url.
- private Handler handler = new Handler();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- text = (TextView) findViewById(id_text);
-
-
- new Thread() {
- @Override
- public void run() {
- try {
- URL httpUrl = new URL(url);
- HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
- conn.setReadTimeout(5000);
- conn.setRequestMethod("GET");
-
- final StringBuffer sb = new StringBuffer();
- BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
- String line;
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- }
- handler.post(new Runnable() {
- @Override
- public void run() {
- text.setText(sb.toString());
- }
- });
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }.start();
- }
- }
最后返回的结果如截图所示:

。成功接收到从服务器返回的JSON数据。
如果需要返回的数据为XML,只要重新拼装URL即可。如:"http://apis.juhe.cn/mobile/get?phone=13429667914&key=9719c91bd4ac2647c67c6cd067b5cb8e&dtype=xml";最后返回的结果为XML,截图如下:
。
最后开发者根据需要,可以对XML和JSON进行解析,完成业务需求。
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!