本文主要整理下关于OkHttp3的一些使用。通过OkHttp框架去请求网络数据,一般包括下面几个步骤:
1. 创建OkHttpClient 对象
2. 创建Request对象(对于get和post请求来说,在创建Request对象时略有不同)
3. 创建Call对象
4. 开始请求,返回Response对象
5. 在Response对象中,获取对应的数据
下面主要列举下如下几种使用情景:
1.同步get请求
2.异步get请求
3.post请求上传键值对
4.post请求上传json串
5.post请求上传文件
6.get请求下载文件
下面会一一列举这六种情况下代码实现。
1.同步get请求
需要说下,关于同步请求的话,不能在UI线程中直接执行,必须放到子线程中去做对应网络请求
/** * 同步get请求 */ private void executeNet(){ //1.创建OkHttpClient对象 OkHttpClient mOkHttpClient = new OkHttpClient(); //2.创建Request对象 Request request = new Request.Builder() .url(URL) .build(); //3.创建Call对象 Call call=mOkHttpClient.newCall(request); //4.开始同步请求,返回Response对象 try { Response mResponse = call.execute(); String result=mResponse.body().string(); Log.i(TAG, "服务器返回结果(同步请求): " + result); Bundle mBundle=new Bundle(); mBundle.putString("result",result); Message msg=new Message(); msg.setData(mBundle); msg.what=1; mHandler.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); } }
异步请求,可以直接在UI线程中去执行,但是回调的onResponse()方法并不是UI线程,所以不能在onResponse方法中直接去操作控件
/** * 异步get请求 */ private void enqueueNet(){ OkHttpClient mOkHttpClient = new OkHttpClient(); final Request request = new Request.Builder() .url(URL) .build(); Call call=mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //需要注意,response.body().string()调用一次后,response中的流就会被关闭 String result=response.body().string(); response.headers("Set-Cookie"); Log.d(TAG,"服务器返回结果(异步请求):"+result); Bundle mBundle=new Bundle(); mBundle.putString("result",result); Message msg=new Message(); msg.setData(mBundle); msg.what=1; mHandler.sendMessage(msg); } }); }
post请求中,在第二步创建Request对象前,需要先创建RequestBody对象来存储需要上传的不同数据
/** * 发送POST请求,上传键值对 **/ private void okHttpPostPairs() { //1.创建OkHttpClient 对象 OkHttpClient mOkHttpClient = new OkHttpClient(); //2.创建Request 对象,在之前,需要先创建RequestBody 对象,用来存储需要上传的数据 RequestBody body = new FormBody.Builder() .add("login_username", "leijx") .add("login_password", "123456") .build(); Request request = new Request.Builder() .url(URL) .post(body) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { List<String> setCookieList = response.headers("Set-Cookie"); Log.i(TAG, "repose result: " + response.body().string()); } }); }
4.post请求上传json串
/** * post请求 * 上传json */ private void enqueueNet_post(){ //1.创建OkHttpClient 对象 OkHttpClient mOkHttpClient = new OkHttpClient(); //2.创建Request 对象,在之前,需要先创建RequestBody 对象,用来存储需要上传的数据 RequestBody mRequestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),"这是一个json串"); Request mRequest = new Request.Builder() .url(URL) .post(mRequestBody) .build(); Call mCall = mOkHttpClient.newCall(mRequest); mCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); }
5.post请求上传文件
/** * POST请求,上传图片 **/ private void okHttpUpLoad() { OkHttpClient mOkHttpClient = new OkHttpClient(); File file = new File(Environment.getExternalStorageDirectory() + "/ic_launcher.png"); //不带参数的RequestBody // RequestBody body = RequestBody.create(MediaType.parse("image/png"),file); //带参数的RequestBody // MultipartBody.Builder builder = new MultipartBody.Builder(); // builder.addFormDataPart("filename", "testpng"); // builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file)); // RequestBody body = builder.build(); RequestBody body = new MultipartBody.Builder() .addFormDataPart("filename", "testpng") .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file)) .build(); Request request = new Request.Builder() .url(URL) .post(body) .addHeader("Cookie", "test") .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { Log.i(TAG, "upload success, repose result: " + response.body().string()); } }); }
/** * 下载文件 **/ private void okHttpDownload() { OkHttpClient mOkHttpClient = new OkHttpClient(); final File file = new File(Environment.getExternalStorageDirectory().toString() + "/default.png"); Request request = new Request.Builder().url(URL).build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.i(TAG, "failure: "); e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { Log.i(TAG, "onResponse"); InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { long total = response.body().contentLength(); Log.e(TAG, "total------>" + total); long current = 0; //获取对应流 is = response.body().byteStream(); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { current += len; fos.write(buf, 0, len); Log.e(TAG, "current------>" + current); } fos.flush(); Log.i(TAG, "download file success"); } catch (IOException e) { Log.e(TAG, e.toString()); } finally { try { if (is != null) { is.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { Log.e(TAG, e.toString()); } } } }); }