JAVA網絡請求和幾種網絡框架

安卓中網絡請求方式 一.HttpUrlConnection:最基礎的,重點
(1)get請求
(2)post請求
(3)get請求數據下載到SD卡中:圖片,視頻,音頻,帶進度條的下載
二.HttpClient:已經過時的,安卓SDK26以後該類已經被谷歌刪掉了
三.Xutils:第三方框架,功能比較全(數據庫,圖片,網絡。。。。),發明這個東西的人想象很豐滿,現實很難維護。
四.OkHttp:第三方框架(重點,老app使用)
這是一個開源項目,是安卓端最火熱的輕量級框架,由移動支付Square公司貢獻(該公司還貢獻了Picasso和LeakCanary) 。
用於替代HttpUrlConnection和Apache HttpClient(android API23 裏已移除HttpClient)
(1)導入依賴implementation ‘com.squareup.okhttp3:okhttp:3.12.1’
(2)創建Okhttpclient對象
(3)創建Request對象
(4)通過client.newCall(request);得到call對象
(5)調用enqueue方法得到Response對象
五.Volley:第三方框架(重點,老app使用)
(0)導入依賴 implementation’eu.the4thfloor.volley:com.android.volley:2015.05.28’
(1)創建RequestQueue請求隊列 (2)創建Request對象:StringRequest和ImageRequest對象
(3)add()添加到請求隊列中
六.Retrofit

網絡:

private String get_url="http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1";
private String post_url="http://www.qubaobei.com/ios/cf/dish_list.php";//缺少page的請求參數 使用post提交

1.原生網絡請求

(1) get請求

private void get() {
	new Thread(new Runnable() {
	@Override
	public void run() {
		StringBuffer stringBuffer=new StringBuffer();
		try {
			URL url = new URL(get_url);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setConnectTimeout(5*1000);//鏈接超時
			urlConnection.setReadTimeout(5*1000);//返回數據超時
			//getResponseCode (1.200請求成功 2.404請求失敗)
			if(urlConnection.getResponseCode()==200){
				//獲得讀取流寫入
				InputStream inputStream = urlConnection.getInputStream();
				byte[] bytes=new byte[1024];
				int len=0;
				while ((len=inputStream.read(bytes))!=-1){
					stringBuffer.append(new String(bytes,0,len));
				}
				}
				} catch (MalformedURLException e) {
			e.printStackTrace();
			} catch (IOException e) {
			e.printStackTrace();
			}
		}
	}).start();
}

(2) post請求

private void post() {
	new Thread(new Runnable() {
	@Override
	public void run() {
		StringBuffer stringBuffer=new StringBuffer();
		try {
			URL url = new URL(post_url);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setConnectTimeout(5*1000);
			urlConnection.setReadTimeout(5*1000);
			//設置請求方式,默認是get
			urlConnection.setRequestMethod("POST");//大寫的POST
			//設置允許輸出
			urlConnection.setDoOutput(true);//允許向服務器提交數據、
			//獲得輸出流寫數據 "&page=1"
			urlConnection.getOutputStream().write("?stage_id=1&limit=10&page=1".getBytes());//請求參數放到請求體
				if(urlConnection.getResponseCode()==200){
					InputStream inputStream = urlConnection.getInputStream();
					byte[] bytes=new byte[1024];
					int len=0;
					while ((len=inputStream.read(bytes))!=-1){
						stringBuffer.append(new String(bytes,0,len));
					}
				}
				} catch (MalformedURLException e) {
				e.printStackTrace();
				} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}).start();
}

2.xutils

需要導入依賴
implementation ‘org.xutils:xutils:3.5.1’

3.OkHttp

需要導入依賴
implementation ‘com.squareup.okhttp3:okhttp:3.12.1’

4.volley

需要導入依賴:
implementation ‘eu.the4thfloor.volley:com.android.volley:2015.05.28’

5.retrofit

個人理解:
retrofit呢也是一種網絡框架,他呢底層封裝的是OkHttp,也可以理解是OkHttp的加強版,其實底層的網絡請求是OkHttp完成的,有疑問說OkHttp來做網絡請求,那麼,爲什麼還要封裝Retrofit呢,那麼retrofit就出來了,Retrofit
僅負責網絡請求接口的封裝。它的一個特點是包含了特別多註解,方便簡化你的代碼量。並且還支持很多的開源庫(著名例子:Retrofit +
RxJava)。

請求方法

項目 Value
@GET GET請求
@POST POST請求

請求參數

註解代碼 說明
@Headers 添加請求頭
@Path 替換路徑
@Query 替代參數值,通常是結合get請求的
@FormUrlEncoded 用表單數據提交
@Field 替換參數值,是結合post請求的

那麼接下來,就可以看看Retrofit的簡單的用法

1.首先我們導入依賴

dependencies {
    // Okhttp庫
    compile 'com.squareup.okhttp3:okhttp:3.1.2'
    // Retrofit庫
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
}

2.創建我們請求的數據類

public class News{
    // 比如我們請求到的JSON串,解析類,也就是我們需要的數據
    }

3.創建我們的網絡請求接口

public interface APi {
    // @GET註解的作用:採用Get方法發送網絡請求
    // getNews(...) = 接收網絡請求數據的方法
    // 其中返回類型爲Call<News>,News是接收數據的類(即上面定義的News類)
    // 如果想直接獲得Responsebody中的內容,可以定義網絡請求返回值爲Call<ResponseBody>
    @Headers("apikey:81bf9da930c7f9825a3c3383f1d8d766")
    @GET("word/word")
    Call<News> getNews(@Query("num") String num,@Query("page")String page);
}

4.最後,完成請求

Retrofit retrofit = new Retrofit.Builder()
        //設置數據解析器
        .addConverterFactory(GsonConverterFactory.create())
        //設置網絡請求的Url地址
        .baseUrl("http://apis.baidu.com/txapi/")
        .build();
// 創建網絡請求接口的實例
mApi = retrofit.create(APi.class);
//對發送請求進行封裝
Call<News> news = mApi.getNews("1", "10");
//發送網絡請求(異步)
news.enqueue(new Callback<News>() {
    //請求成功時回調
    @Override
    public void onResponse(Call<News> call, Response<News> response) {
       //請求處理,輸出結果-response.body().show();
    }

    @Override
    public void onFailure(Call<News> call, Throwable t) {
       //請求失敗時候的回調
    }
});
//發送網絡請求(同步)
Response<Reception> response = news.execute();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章