安卓okhttp的常见用法

来源:互联网 发布:淘宝丝袜买家秀 编辑:程序博客网 时间:2024/06/07 05:23

1.git地址:https://github.com/square/okhttp

2.添加依赖: compile 'com.squareup.okhttp3:okhttp:3.9.0' 

3.代码

/** * okhttp异步请求,Get方法 */public void okHttpGet() {    OkHttpClient client = new OkHttpClient();    Request request = new Request            .Builder()            .url("http://japi.juhe.cn/joke/content/list.from")            .get()            .build();    client.newCall(request).enqueue(new Callback() {        @Override        public void onFailure(Call call, IOException e) {            Log.e(TAG, "onFailure: ");        }        @Override        public void onResponse(Call call, Response response) throws IOException {            Log.e(TAG, "onResponse: " + response.body().string());        }    });}/** * okhttp同步请求,Get方法 */public void okHttpGet2() throws IOException {    OkHttpClient client = new OkHttpClient();    Request request = new Request            .Builder()            .url("http://japi.juhe.cn/joke/content/list.from")            .get()            .build();    Response execute = client.newCall(request).execute();    String string = execute.body().string();    Log.e(TAG, "okHttpGet2: " + string);}/** * okhttp异步请求,Post方法 */public void okHttpPost() {    OkHttpClient client = new OkHttpClient();    //创建Form表单对象,可以add多个键值队    FormBody formBody = new FormBody.Builder()            .add("key", "123")            .add("param", "value")            .build();    //创建一个Request    Request request = new Request.Builder()            .url("http://japi.juhe.cn/joke/content/list.from")            .post(formBody)            .build();    //发起异步请求,并加入回调    client.newCall(request).enqueue(new Callback() {        @Override        public void onFailure(Call call, IOException e) {            Log.e(TAG, "onFailure: ");        }        @Override        public void onResponse(Call call, Response response) throws IOException {            Log.e(TAG, "onResponse: " + response.body().string());        }    });}/** * okhttp同步请求,Post方法 */public void okHttpPost2() throws IOException {    OkHttpClient client = new OkHttpClient();    FormBody formBody = new FormBody.Builder()            .add("key", "123")            .add("param", "value")            .build();    Request request = new Request.Builder()            .url("http://japi.juhe.cn/joke/content/list.from")            .post(formBody)            .build();    Response execute = client.newCall(request).execute();    String string = execute.body().string();    Log.e(TAG, "okHttpPost2: " + string);}
/** * okhttp异步请求,Post方法上传单个文件 */private void postFile() {    OkHttpClient mOkHttpClient = new OkHttpClient();    File file = new File("/sdcard/demo.txt");    Request request = new Request.Builder()            .url("https://api.github.com/markdown/raw")            .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), file))            .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, response.body().string());        }    });}
/** * okhttp异步请求,Post方法上传多个文件 */public void upload() { OkHttpClient client = new OkHttpClient(); //多个文件集合 List<File> list = new ArrayList<>(); MultipartBody.Builder builder = new MultipartBody.Builder(); //设置为表单类型 builder.setType(MultipartBody.FORM); //添加表单键值 builder.addFormDataPart("param", "value"); for (File file : list) { //添加多个文件 RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); builder.addFormDataPart("files", file.getName(), fileBody); } Request request = new Request.Builder() .url("http://192.168.1.8/upload/UploadServlet") .post(builder.build()) .build(); //发起异步请求,并加入回调 client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { Log.e("okHttp", "updLoad=" + response.body().string()); } });}
/** * okhttp异步请求,Post方法上传字符串 */private void postString() throws IOException {    OkHttpClient client = new OkHttpClient();    String postBody = ""            + "Releases\n"            + "--------\n"            + "\n"            + " * zhangfei\n"            + " * guanyu\n"            + " * liubei\n";    Request request = new Request.Builder()            .url("https://api.github.com/markdown/raw")            .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody))            .build();    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 {            Log.e(TAG, "onResponse: " + response.body().string());        }    });}
/** * 下载文件 */public void downLoadFile() { OkHttpClient client = new OkHttpClient(); final File file = new File(Environment.getExternalStorageDirectory(), "123.apk"); Request request = new Request.Builder().url("http://www.mfmatches.com/mfmatches.apk").build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "下载失败"); } @Override public void onResponse(Call call, Response response) throws IOException { 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(); } 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()); } } } });}

原创粉丝点击