安卓GET與POST網(wǎng)絡(luò)請求的三種方式
我們的應(yīng)用常常要聯(lián)網(wǎng)取得網(wǎng)絡(luò)上的數(shù)據(jù),然后進行解析,必須要先取到數(shù)據(jù)之后才能進行下一步的業(yè)務(wù)。
故網(wǎng)絡(luò)請求是常用的操作,下面我介紹常用的三種方式,
- 第一是比較原始的方法,使用HttpURLConnection,
- 第二是Volley框架,
- 第三是xutils3框架。
1.HttpURLConnection方法
這是基于網(wǎng)絡(luò)通信HTTP協(xié)議的網(wǎng)絡(luò)請求,其它兩種框架也是基于HTTP協(xié)議的。HTTP協(xié)議是一款基于短連接的協(xié)議,每次交互完畢后連接斷開,而HTTP請求又分為GET和POST兩種方式,GET請求比較簡單,只需要在網(wǎng)址后面用?拼接請求的資源路徑,如百度圖片輸入動漫關(guān)鍵字的地址
可以看到index?后面跟了很多&連接的項目,這個&就是代表了一個個搜索的條件,而最后一個word=%E5%8A%A8%E6%BC%AB又是什么意思呢
就是輸入的兩個字”動漫”,這就是UTF-8編碼后的字節(jié),中文一個字符會編成三個字節(jié),這是用16進制表示了一個字節(jié)。
從中也可以看到GET請求的一個限制,那就是不能傳遞中文,也不適合大數(shù)據(jù)量的數(shù)據(jù)提交。
而POST則就沒這個限制,且安全性也比GET請求高,總結(jié)就是簡單的網(wǎng)絡(luò)請求用GET,比較復(fù)雜的要與服務(wù)器與交互的就用POST請求。
接下來就是發(fā)送GET請求和POST請求了。
GET請求
//1. URL URL url = new URL("http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB"); //2. HttpURLConnection HttpURLConnection conn=(HttpURLConnection)url.openConnection(); //3. set(GET) conn.setRequestMethod("GET"); //4. getInputStream InputStream is = conn.getInputStream(); //5. 解析is,獲取responseText,這里用緩沖字符流 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while((line=reader.readLine()) != null){ sb.append(line); } //獲取響應(yīng)文本 String responseText = sb.toString();
POST請求
//1. URL URL url = new URL("http://image.baidu.com/search/index"); //2. HttpURLConnection HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //3. POST conn.setRequestMethod("POST"); //4. Content-Type,這里是固定寫法,發(fā)送內(nèi)容的類型 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //5. output,這里要記得開啟輸出流,將自己要添加的參數(shù)用這個輸出流寫進去,傳給服務(wù)端,這是socket的基本結(jié)構(gòu) conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); String param = "tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB"; //一定要記得將自己的參數(shù)轉(zhuǎn)換為字節(jié),編碼格式是utf-8 os.write(param.getBytes("utf-8")); os.flush(); //6. is InputStream is = conn.getInputStream(); //7. 解析is,獲取responseText BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while((line=reader.readLine()) != null){ sb.append(line); } //獲取響應(yīng)文本 String responseText = sb.toString();
2.Volley框架
GET請求
//1. 創(chuàng)建RequestQueue,這是一個請求隊列,相當(dāng)于消息機制處理 private RequestQueue mQueue = Volley.newRequestQueue(this); //2. StringRequest String url = "http://www.baidu.com"; StringRequest req = new StringRequest(url, new Listener<String>() { //請求成功后回調(diào) 在主線程中執(zhí)行 public void onResponse(String responseText) { //解析json 封裝結(jié)果數(shù)據(jù) Gson gson = new Gson(); //這里用的Gson解析JSON字符串 User result=gson.fromJson(responseText,RequestResult.class); } }, new ErrorListener() { //請求出錯時 執(zhí)行回調(diào) 在主線程中執(zhí)行 public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); //把req 添加到 請求隊列中,一定要記得這一步,不然就相當(dāng)于沒有發(fā)送請求 mQueue.add(req);
POST請求
private RequestQueue mQueue; //post請求要用commonRequest請求實現(xiàn) String url="www.baidu.com"; CommonRequest request = new CommonRequest(Request.Method.POST,url,new Response.Listener<String>() { public void onResponse(String response) { try { //這里是請求成功后調(diào)用的接口,用JSON工具解析數(shù)據(jù) JSONObject obj = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); } } },new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { } }){ //如果用POST請求,要添加參數(shù),一定要重寫這個方法來添加參數(shù) @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> resultMap = new HashMap<String, String>(); //這里的添加的具體參數(shù) resultMap.put("username",user.getName()); resultMap.put("userAge",user.getAge()); resultMap.put("userGender",user.getGender()); resultMap.put("userSchool",user.getSchool()); return resultMap; } }; mQueue.add(request); }
3.Xutils3框架
GET請求
//第一步,新建一個請求參數(shù)對象 RequestParams params=new RequestParams("www.baidu.com?inm=2"); //直接調(diào)用x.http().get()方法,這里注意x是要用全局MyApplication中初始化后才可以使用,初始化方法為x.Ext.init(this) x.http().get(params, new Callback.CommonCallback<String>() { @Override public void onCancelled(CancelledException arg0) { } @Override public void onError(Throwable arg0, boolean arg1) { Log.i("hap.zhu", "http_on_error,請求網(wǎng)絡(luò)數(shù)據(jù)失敗"); } @Override public void onFinished() { } @Override public void onSuccess(String result) { Log.i("hap.zhu", "請求數(shù)據(jù)結(jié)果為:"+result); Gson gson=new Gson(); Result result=gson.fromJson(result,Result.class); Log.i("hap.zhu", "加載結(jié)果為:"+result.toString()); } });
POST請求
//方法同GET,就是這么簡單,網(wǎng)絡(luò)請求成功會回調(diào)監(jiān)聽器里的success接口,直接處理數(shù)據(jù)結(jié)果就行 RequestParams params=new RequestParams("www.baidu.com"); params.addBodyParameter("email", username); params.addBodyParameter("password", password); x.http().post(params, new CommonCallback<String>() { @Override public void onCancelled(CancelledException arg0) { } @Override public void onError(Throwable arg0, boolean arg1) { //網(wǎng)絡(luò)錯誤也會提示錯誤 callback.Error(arg0.toString()); } @Override public void onFinished() { } @Override public void onSuccess(String result) { Gson gson=new Gson(); LoginResult loginResult=gson.fromJson(result, LoginResult.class);
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
- 詳解Android:向服務(wù)器提供數(shù)據(jù)之get、post方式
- android AsynTask處理返回數(shù)據(jù)和AsynTask使用get,post請求
- Android中post和get的提交方式【三種】
- Android中使用OkHttp包處理HTTP的get和post請求的方法
- Android中使用HttpURLConnection實現(xiàn)GET POST JSON數(shù)據(jù)與下載圖片
- android平臺HttpGet、HttpPost請求實例
- android使用url connection示例(get和post數(shù)據(jù)獲取返回數(shù)據(jù))
- Android發(fā)送GET與POST請求的DEMO詳解
- android之HttpPost&HttpGet使用方法介紹
- Android HttpClient GET或者POST請求基本使用方法
相關(guān)文章
Android計時器控件Chronometer應(yīng)用實例
這篇文章主要為大家詳細介紹了Android計時器控件Chronometer應(yīng)用實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09Android實現(xiàn)圖片循環(huán)播放的實例方法
2013-05-05Android中ViewPager獲取當(dāng)前顯示的Fragment
這篇文章主要介紹了Android中ViewPager獲取當(dāng)前顯示的Fragment的兩種方法,一種是使用 getSupportFragmentManager().findFragmentByTag()方法,另一種是重寫適配器的 setPrimaryItem()方法,有需要的朋友可以參考借鑒,下面來一起看看吧。2017-01-01