原本是想圍繞着HttpClient講解的,後來發先Android4.4以後okhttp代替了hc,因此將再也不講解hccss
okhttp的簡單使用,主要包含:java
使用okhttp前首先要添加依賴json
compile 'com.squareup.okhttp3:okhttp:3.9.0'
對了網絡加載庫,那麼最多見的確定就是http get請求了,好比獲取一個網頁的內容數組
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); String string = response.body().string(); System.out.println(string); }
運行結果tomcat
以上就是發送一個get請求的步驟,首先構造一個Request對象,參數最起碼有個url,固然你能夠經過Request.Builder設置更多的參數好比:header、method等。服務器
而後經過request的對象去構造獲得一個Call對象,相似於將你的請求封裝成了任務,既然是任務,就會有execute()和cancel()等方法。網絡
最後,咱們但願以異步的方式去執行請求,因此咱們調用的是call.enqueue,將call加入調度隊列,而後等待任務執行完成,咱們在Callback中便可獲得結果。session
onResponse回調的參數是response,通常狀況下,好比咱們但願得到返回的字符串,能夠經過
response.body().string()
獲取;若是但願得到返回的二進制字節數組,則調用response.body().bytes();
若是你想拿到返回的inputStream,則調用response.body().byteStream()
app
不少時候咱們會須要經過POST方式把鍵值對數據傳送到服務器。 OkHttp提供了很方便的方式來作這件事情。好比提交用戶名和密碼用來登陸異步
post提交鍵值對其實和get方法之多了一個RequestBody,用來添加鍵值對
get提交鏈接以下
http://192.168.56.1:8080/LoginServlet?username=abc&password=123
post提交鏈接以下
OkHttpClient client = new OkHttpClient(); RequestBody requestBody=new FormBody.Builder() .add("username","abc") .add("password","123") .build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = client.newCall(request).execute(); String string = response.body().string(); System.out.println(string); }
是否是比hc簡單多了,這裏須要注意到一點是最新版的okhttp,原來的FormEncodingBuilder被FormBody代替了
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string();
new Thread(){public void run(){ OkHttpClient client = new OkHttpClient(); Request request=new Request.Builder().url("http://192.168.56.1:8080/tomcat.png").build(); try { Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("下載失敗"); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream in=response.body().byteStream(); FileOutputStream fos=new FileOutputStream(new File(getFilesDir(),"11.png")); int len=0; byte []bytes=new byte[1024]; while ((len=in.read(bytes))!=-1){ fos.write(bytes,0,len); } fos.flush(); } }); } catch (Exception e) { e.printStackTrace(); } }}.start();
其實仔細看仍是和上面的get請求差很少,無非就是get下載了,這裏就只是改變了
Call call = client.newCall(request);
call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { //鏈接失敗 } @Override public void onResponse(Call call, Response response) throws IOException { //鏈接成功 }
public static void doFile(String url, String pathName, String fileName, Callback callback) { //判斷文件類型 MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName)); //建立文件參數 MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart(MEDIA_TYPE.type(), fileName, RequestBody.create(MEDIA_TYPE, new File(pathName))); //發出請求參數 Request request = new Request.Builder() .header("Authorization", "Client-ID " + "9199fdef135c122") .url(url) .post(builder.build()) .build(); Call call = getInstance().newCall(request); call.enqueue(callback); } /** * 根據文件路徑判斷MediaType * * @param path * @return */ private static String judgeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = fileNameMap.getContentTypeFor(path); if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; }