上一篇介紹了關于OkHttp進行GET請求和POST請求最基本的用法,下面繼續介紹OkHttp的使用。 上一篇地址:http://blog.csdn.net/james_shu/article/details/55270728
首先來介紹一下有關于OkHttp將json作為請求參數來請求服務器端并得到響應的使用流程:
OkHttpClient client=new OkHttpClient(); RequestBody requestBody=RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),"{'name':'wangshu','age':18}"); Request request=new Request.Builder().post(requestBody).url("http://10.0.2.2:8088/TestS我們可以使用OkHTTP來將流作為請求體以POST的方式請求服務器,通過這種方式我們可以實現文件上傳: OkHttpClient client = new OkHttpClient(); final File file = new File(Environment.getExternalStorageDirectory(), "aaa.txt"); RequestBody requestBody=new RequestBody() { @Override public MediaType contentType() { return MediaType.parse("text/x-markdown; charset=utf-8"); } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line=null; while ((line=reader.readLine())!=null){ sink.write(line.getBytes()); } } }; Request request=new Request.Builder().url("http://10.0.2.2:8088/TestSpringMVC/uploadfile") .post(requestBody) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, final Response response) throws IOException { runOnUiThread(new Runnable() { @Override public void run() { try { Toast.makeText(getApplicationContext(),response.body().string(),Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } }); } });下面繼續介紹OkHttp使用緩存:
OkHttpClient.Builder builder=new OkHttpClient.Builder(); //設置緩存 int cacheSize=10*1024*1024;//10M Cache cache=new Cache(getCacheDir(),cacheSize); builder.cache(cache); final OkHttpClient client=builder.build(); final Request request=new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); new Thread(){ @Override public void run() { super.run(); try { Response response1=client.newCall(request).execute(); System.out.println("Response 1 response: " + response1); System.out.println("Response 1 cache response: " + response1.cacheResponse()); System.out.println("Response 1 network response: " + response1.networkResponse()); String response1Body = response1.body().string(); Response response2 = client.newCall(request).execute(); if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2); String response2Body = response2.body().string(); System.out.println("Response 2 response: " + response2); System.out.println("Response 2 cache response: " + response2.cacheResponse()); System.out.println("Response 2 network response: " + response2.networkResponse()); System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body)); } catch (IOException e) { e.printStackTrace(); } } }.start();新聞熱點
疑難解答