之前使用了開源網絡請求庫Volley進行了Http GET請求。這次我們讨論使用Volley進行POST請求。POST請求比GET稍微複雜一點點。可以認為是建立在GET的基礎上。POST使發送的url更加簡潔,安全,高效,使能發送更大量的資料。
該例子仍舊是對聚合資料的手機号碼歸屬地進行請求,傳回JSON資料,顯示在TextView上。不要忘了在AndroidMenifest.xml内加入Internet權限。直接上代碼:
public class MainActivity extends Activity {
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.id_text);
volleyPost();
}
public void volleyPost() {
String url = "http://apis.juhe.cn/mobile/get";//這裡和GET方式不同的是去掉了“?”後面的參數;
/**
* 第一個參數指定了請求方式,第二個參數指定了url,第三個參數指定了正确通路的傳回結果,第四個參數是通路失敗後的業務邏輯;
*
*/
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String result) {
text.setText(result);//傳回結果顯示在TextView;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
text.setText("未能請求到資料");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {//在這裡封裝了需要發送的參數;
HashMap<String, String> map = new HashMap<>();
map.put("phone", "13429667914");//以鍵值對的形式存放;
map.put("key", "9719c91bd4ac2647c67c6cd067b5cb8e");
return map;
}
};
Volley.newRequestQueue(getApplicationContext()).add(request);//加入請求隊列;
}//volleyPost();
}
最後的實作效果如下截圖所示:
。
至此,已經成功實作了Http POST請求。可以根據業務需求對傳回的JSON資料進行解析。
附Volley下載下傳位址:http://pan.baidu.com/s/1dDFDbdJ