安卓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,這里是固定寫法,發(fā)送內(nèi)容的類型
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//5. output,這里要記得開(kāi)啟輸出流,將自己要添加的參數(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)于沒(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ù),一定要重寫這個(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實(shí)現(xiàn)單項(xiàng)、多項(xiàng)選擇操作
這篇文章主要介紹了Android實(shí)現(xiàn)單項(xiàng)、多項(xiàng)選擇操作的相關(guān)資料,單項(xiàng)選擇、多項(xiàng)選擇操作在項(xiàng)目開(kāi)發(fā)中經(jīng)常應(yīng)用,感興趣的小伙伴們可以參考一下2016-04-04
Android利用ViewPager實(shí)現(xiàn)可滑動(dòng)放大縮小畫廊效果
這篇文章主要介紹了Android利用ViewPager實(shí)現(xiàn)可滑動(dòng)放大縮小畫廊效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08
利用Kotlin Tools如何快速添加Kotlin依賴詳解
這篇文章主要給大家介紹了關(guān)于利用Kotlin Tools如何快速添加Kotlin依賴的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11
Android實(shí)現(xiàn)自動(dòng)變換大小的組件ViewPager2
這篇文章主要介紹了Android實(shí)現(xiàn)自動(dòng)變換大小的組件ViewPager2,ViewPager2最顯著的特點(diǎn)是基于RecyclerView實(shí)現(xiàn),RecyclerView是目前Android端最成熟的AdapterView解決方案2023-03-03
Android中fragment+viewpager實(shí)現(xiàn)布局
這篇文章主要為大家詳細(xì)介紹了Android中fragment+viewpager實(shí)現(xiàn)布局效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
Android的HTTP操作庫(kù)Volley的基本使用教程
這篇文章主要介紹了Android的HTTP操作庫(kù)Volley的基本使用教程,包括JSON請(qǐng)求與圖片加載等用法的實(shí)例,需要的朋友可以參考下2016-05-05
Android系統(tǒng)進(jìn)程間通信(IPC)機(jī)制Binder中的Server啟動(dòng)過(guò)程源代碼分析
本文主要介紹Android IPC機(jī)制Binder中的Server啟動(dòng)過(guò)程源代碼,這里對(duì)Binder 中Server 啟動(dòng)過(guò)程中的源碼做了詳細(xì)的介紹,有研究Android源碼 Binder 通信的小伙伴可以參考下2016-08-08

