您好,登錄后才能下訂單哦!
我們的應(yīng)用常常要聯(lián)網(wǎng)取得網(wǎng)絡(luò)上的數(shù)據(jù),然后進(jìn)行解析,必須要先取到數(shù)據(jù)之后才能進(jìn)行下一步的業(yè)務(wù)。
故網(wǎng)絡(luò)請(qǐng)求是常用的操作,下面我介紹常用的三種方式,
1.HttpURLConnection方法
這是基于網(wǎng)絡(luò)通信HTTP協(xié)議的網(wǎng)絡(luò)請(qǐng)求,其它兩種框架也是基于HTTP協(xié)議的。HTTP協(xié)議是一款基于短連接的協(xié)議,每次交互完畢后連接斷開,而HTTP請(qǐng)求又分為GET和POST兩種方式,GET請(qǐng)求比較簡(jiǎn)單,只需要在網(wǎng)址后面用?拼接請(qǐng)求的資源路徑,如百度圖片輸入動(dòng)漫關(guān)鍵字的地址
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,
可以看到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則就沒這個(gè)限制,且安全性也比GET請(qǐng)求高,總結(jié)就是簡(jiǎn)單的網(wǎng)絡(luò)請(qǐng)求用GET,比較復(fù)雜的要與服務(wù)器與交互的就用POST請(qǐng)求。
接下來就是發(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,這里是固定寫法,發(fā)送內(nèi)容的類型 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //5. output,這里要記得開啟輸出流,將自己要添加的參數(shù)用這個(gè)輸出流寫進(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)于沒有發(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ù),一定要重寫這個(gè)方法來添加參數(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)聽器里的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é)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)億速云的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。