安卓GET與POST網(wǎng)絡(luò)請(qǐng)求的三種方式
我們的應(yīng)用常常要聯(lián)網(wǎng)取得網(wǎng)絡(luò)上的數(shù)據(jù),然后進(jìn)行解析,必須要先取到數(shù)據(jù)之后才能進(jìn)行下一步的業(yè)務(wù)。
故網(wǎng)絡(luò)請(qǐng)求是常用的操作,下面我介紹常用的三種方式,
- 第一是比較原始的方法,使用HttpURLConnection,
- 第二是Volley框架,
- 第三是xutils3框架。
1.HttpURLConnection方法
這是基于網(wǎng)絡(luò)通信HTTP協(xié)議的網(wǎng)絡(luò)請(qǐng)求,其它兩種框架也是基于HTTP協(xié)議的。HTTP協(xié)議是一款基于短連接的協(xié)議,每次交互完畢后連接斷開(kāi),而HTTP請(qǐng)求又分為GET和POST兩種方式,GET請(qǐng)求比較簡(jiǎn)單,只需要在網(wǎng)址后面用?拼接請(qǐng)求的資源路徑,如百度圖片輸入動(dòng)漫關(guān)鍵字的地址
可以看到index?后面跟了很多&連接的項(xiàng)目,這個(gè)&就是代表了一個(gè)個(gè)搜索的條件,而最后一個(gè)word=%E5%8A%A8%E6%BC%AB又是什么意思呢
就是輸入的兩個(gè)字”動(dòng)漫”,這就是UTF-8編碼后的字節(jié),中文一個(gè)字符會(huì)編成三個(gè)字節(jié),這是用16進(jìn)制表示了一個(gè)字節(jié)。
從中也可以看到GET請(qǐng)求的一個(gè)限制,那就是不能傳遞中文,也不適合大數(shù)據(jù)量的數(shù)據(jù)提交。
而POST則就沒(méi)這個(gè)限制,且安全性也比GET請(qǐng)求高,總結(jié)就是簡(jiǎn)單的網(wǎng)絡(luò)請(qǐng)求用GET,比較復(fù)雜的要與服務(wù)器與交互的就用POST請(qǐng)求。
接下來(lái)就是發(fā)送GET請(qǐng)求和POST請(qǐng)求了。
GET請(qǐng)求
//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請(qǐng)求
//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,這里是固定寫(xiě)法,發(fā)送內(nèi)容的類(lèi)型 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //5. output,這里要記得開(kāi)啟輸出流,將自己要添加的參數(shù)用這個(gè)輸出流寫(xiě)進(jìn)去,傳給服務(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請(qǐng)求
//1. 創(chuàng)建RequestQueue,這是一個(gè)請(qǐng)求隊(duì)列,相當(dāng)于消息機(jī)制處理 private RequestQueue mQueue = Volley.newRequestQueue(this); //2. StringRequest String url = "http://www.baidu.com"; StringRequest req = new StringRequest(url, new Listener<String>() { //請(qǐng)求成功后回調(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() { //請(qǐng)求出錯(cuò)時(shí) 執(zhí)行回調(diào) 在主線程中執(zhí)行 public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); //把req 添加到 請(qǐng)求隊(duì)列中,一定要記得這一步,不然就相當(dāng)于沒(méi)有發(fā)送請(qǐng)求 mQueue.add(req);
POST請(qǐng)求
private RequestQueue mQueue; //post請(qǐng)求要用commonRequest請(qǐng)求實(shí)現(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 { //這里是請(qǐng)求成功后調(diào)用的接口,用JSON工具解析數(shù)據(jù) JSONObject obj = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); } } },new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { } }){ //如果用POST請(qǐng)求,要添加參數(shù),一定要重寫(xiě)這個(gè)方法來(lái)添加參數(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請(qǐng)求
//第一步,新建一個(gè)請(qǐng)求參數(shù)對(duì)象 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,請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)失敗"); } @Override public void onFinished() { } @Override public void onSuccess(String result) { Log.i("hap.zhu", "請(qǐng)求數(shù)據(jù)結(jié)果為:"+result); Gson gson=new Gson(); Result result=gson.fromJson(result,Result.class); Log.i("hap.zhu", "加載結(jié)果為:"+result.toString()); } });
POST請(qǐng)求
//方法同GET,就是這么簡(jiǎn)單,網(wǎng)絡(luò)請(qǐng)求成功會(huì)回調(diào)監(jiān)聽(tīng)器里的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ò)錯(cuò)誤也會(huì)提示錯(cuò)誤 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é)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
- 詳解Android:向服務(wù)器提供數(shù)據(jù)之get、post方式
- android AsynTask處理返回?cái)?shù)據(jù)和AsynTask使用get,post請(qǐng)求
- Android中post和get的提交方式【三種】
- Android中使用OkHttp包處理HTTP的get和post請(qǐng)求的方法
- Android中使用HttpURLConnection實(shí)現(xiàn)GET POST JSON數(shù)據(jù)與下載圖片
- android平臺(tái)HttpGet、HttpPost請(qǐng)求實(shí)例
- android使用url connection示例(get和post數(shù)據(jù)獲取返回?cái)?shù)據(jù))
- Android發(fā)送GET與POST請(qǐng)求的DEMO詳解
- android之HttpPost&HttpGet使用方法介紹
- Android HttpClient GET或者POST請(qǐng)求基本使用方法
相關(guān)文章
Android系統(tǒng)對(duì)話框使用詳解(最詳細(xì))
這篇文章主要介紹了Android系統(tǒng)對(duì)話框使用詳解(最詳細(xì)),需要的朋友可以參考下2017-10-10Flutter實(shí)現(xiàn)不同縮放動(dòng)畫(huà)效果詳解
這篇文章主要為大家詳細(xì)介紹了Flutter利用不同組件(ScaleTransition、SizeTransition、AnimatedSize和AnimatedBuilder)實(shí)現(xiàn)不同縮放動(dòng)畫(huà)效果,感興趣的可以動(dòng)手嘗試一下2022-06-06Android計(jì)時(shí)器控件Chronometer應(yīng)用實(shí)例
這篇文章主要為大家詳細(xì)介紹了Android計(jì)時(shí)器控件Chronometer應(yīng)用實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09Android實(shí)現(xiàn)圖片循環(huán)播放的實(shí)例方法
2013-05-05Kotlin類(lèi)的繼承實(shí)現(xiàn)詳細(xì)介紹
這篇文章主要介紹了Kotlin類(lèi)的繼承,在Java中類(lèi)的繼承默認(rèn)是繼承父類(lèi)的方法和參數(shù)的,但是在kotlin中默認(rèn)是不繼承的,那么我們接下來(lái)來(lái)驗(yàn)證2022-09-09flutter實(shí)現(xiàn)發(fā)送驗(yàn)證碼功能
這篇文章主要為大家詳細(xì)介紹了flutter發(fā)送驗(yàn)證碼功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07Android中ViewPager獲取當(dāng)前顯示的Fragment
這篇文章主要介紹了Android中ViewPager獲取當(dāng)前顯示的Fragment的兩種方法,一種是使用 getSupportFragmentManager().findFragmentByTag()方法,另一種是重寫(xiě)適配器的 setPrimaryItem()方法,有需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-01-01