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();
-
- @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("POST");
-
- String content = "phone=13429667914&key=9719c91bd4ac2647c67c6cd067b5cb8e";
- OutputStream is = conn.getOutputStream();
- is.write(content.getBytes());
-
- 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();
- }
- }
运行程序后,服务器返回的结果如图:

。成功通过post方式获取服务器数据。
通过比较GET方式和POST方式,其实两者是十分类似的。只是POST方式把需要发送的消息单独抽取出来进行拼接,而不是嵌入到URL中,相对来说更加安全。区别只在于以下4行代码(把URL中“?”之后的内容抽取出来):
- private String url = "http://apis.juhe.cn/mobile/get";//向服务器请求的url.
-
-
- String content = "phone=13429667914&key=9719c91bd4ac2647c67c6cd067b5cb8e";
- OutputStream is = conn.getOutputStream();
- is.write(content.getBytes());
这样就可以方便的进行GET,POST请求了。(对于返回XML格式的就不再赘述了)。
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!