第一組:HttpURLConnection類
從服務器獲取數(shù)據(jù)可以總結(jié)為這幾步:
# GET請求方式的關鍵代碼:
URL url = new URL(netPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMedthod("GET")//沒有寫這個方法雁芙,就默認為get請求方式轧膘,
conn.connect();//發(fā)起連接,
if(conn.getResponseCode==200){//表示連接成功
InputStream is = conn.getInputStream();//從服務器端返回的結(jié)果是以流的形式回來
}
# POST請求關鍵代碼
conn.setRequestMethod("POST")
conn.setDoOutput(true);//設置允許寫出數(shù)據(jù)兔甘,默認不允許谎碍,因為默認就是GET請求方式
conn.setDoInput(true);//設置當前鏈接可以從服務器獲取數(shù)據(jù),默認就是true,就是允許的
Outputstream os = conn.getOutputstream();
os.write(("use=abc&ups=123").getBytes());
os.flush;
conn.connect();//發(fā)起連接
```
第二組:OkHttp:
這是square公司推出的處理Http協(xié)議的網(wǎng)絡請求的工具類
- 一般的get請求洞焙;
- 一般的post請求蟆淀;
- 基于http下載文件;
- 加載圖片澡匪;
- 支持請求回調(diào)熔任,直接返回對象或者是對象集合
- 支持session的保持
GET請求方式的關鍵代碼
OkHttpClient client = new OkHttpClient();//得到客戶端
Request.Builder builder = new Request.Builder();//里面封裝了Builder類作為請求類的靜態(tài)內(nèi)部類
builder.url(netPath);
builder.get();//指定為get請求方式
Request request =builder.build();//采用了構建者模式完成得到請求
//一般使用一句話來完成Request request = new Request.Builder().url(netPath).get().build();
Response response = client.newCall(request).execute();//客戶端發(fā)起請求,并且得到響應的對象
if(response.isSuccessful()){
//表示聯(lián)網(wǎng)成功了
//可以獲得響應的信息唁情,
byte[] data = response.body().bytes疑苔;
String str = response.body().String();
//可以發(fā)現(xiàn),信息都是存在response.body()中甸鸟。
}
Post請求方式的關鍵代碼
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody,Builder();//請求參數(shù)惦费,是放在了RequestBody中
body.add("useName","tom")//是以鍵值對的形式來存貯數(shù)據(jù)
body.add("password","122")
.build();//也是采用的構建者模式
Request request = new Request.Builder().url(netPath).post(body).build();
//之后就與get方式類似了,不同的是處理看你需求
第三組HttpClient
由apache推出的獲取網(wǎng)絡請求數(shù)據(jù)的框架抢韭。
一般使用DefaultHttpClient子類去實現(xiàn)
GET請求方式的關鍵代碼
HttpClient client = new DefaultHttpClient();//也是通過先得到客戶端
HttpGet httpGet = new HttpGet(netPath);//得到httpGet對象薪贫,直接將參數(shù)路徑傳遞進入
HttpResponse response =client.execute(httpGet);//直接發(fā)起請求
if(response.getStatasLine().getStatusCode()==200){
//表示如果連接網(wǎng)絡成功的話
HttpEntity entity = response.getEntity()//獲取響應實體
InputStream is = entity.getContent();//獲取里面的內(nèi)容
//本身也提供了一中封裝好的處理方式
String str = EntityUtils.toString(entity);
byte[] data = EntityUtils.toByteArray(entity);
}
POST請求方式的關鍵代碼
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(netPath);//表明是post的請求方式
List<BasicNameValuePair> paramters = new ArrayList<>();//創(chuàng)建一個容器用于提交數(shù)據(jù)的保存
BasicNameValuePair p = new BasicNameValuePair("user","password");//得到一個對象
paramters.add(p);
HttpEntity entity = new UrlEncodedFormEntity(paramters);//將參數(shù)封裝到請求實體中
post.setEntitiy(entity);//將請求實體放在Post里面。
//之后就是發(fā)起請求就可以了
HttjpResponse response = client.execute(post);