Okhttp 사용 방법

6182 단어
캐시 Ceche
 File direction=new File("/storage/emulated/0/dayhc");
        long hcMax=1024*1024*100;
        //       
        Cache cache=new Cache(direction,hcMax);
        // okhttp
        OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache)// 
                .build();

파일 업로드
  private void upload() {
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/octet-stream");
        File file = new File("/storage/emulated/0/mm.png");
        File file = new File("/storage/emulated/0/mm.png");
        if (file.exists()) {//   file.exists() true 
            RequestBody requestBody = RequestBody.create(mediaType, file);
            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), requestBody)
                    .build();
            Request request = new Request.Builder()
                    .url(mUpFileUrl)
                    .post(multipartBody)
                    .build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    String str = e.getMessage();
                    Log.i(TAG, "onResponse : " + str);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    Log.i(TAG, "onResponse : " + str);
//                    UploadResultBean uploadResultBean = new Gson().fromJson(str, UploadResultBean.class);
                    try {
                        JSONObject jsonObject = new JSONObject(str);
                        int code= (int) jsonObject.get("code");
                        Log.i(TAG, "onResponse  code: " + code);
                        if(code == 200){// ,  url    , , 
                            JSONObject data = jsonObject.getJSONObject("data");
                            String url = (String) data.get("url");
                            Log.i(TAG, "onResponse   : " + url);
                            Glide.with(MainActivity.this).load(url).into(mHeaderImg);// 
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//                    if (uploadResultBean.getCode() == 200) {// 
//                        String url = uploadResultBean.getData().getUrl();// url
//                        Glide.with(MainActivity.this).load(url).into(mHeaderImg);// 
//
//                    }
                }
            });
        }


From 양식을 제출하면 post 제출 키 값 쌍
  private void login() {
        OkHttpClient okHttpClient = new OkHttpClient();
        //post , FormBody.Builder , 
        RequestBody requestBody = new FormBody.Builder()
                .add("username", "qawsedrf")
                .add("password", "qazwsxedc")
                .build();

        Request request = new Request.Builder()
                .url(loginUrl)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String str = e.getMessage();
                Log.i(TAG, " : " + str);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Log.i(TAG, "onResponse : " + str);
                //json 
                LoginResultBean loginResultBean = new Gson().fromJson(str, LoginResultBean.class);
                int errorCode = loginResultBean.getErrorCode();
                handler.sendMessage(handler.obtainMessage(1, errorCode));
            }
        });

    }

//okhttp 다운로드 파일
 OkHttpClient build = new OkHttpClient.Builder()
                .build();
        Request build1 = new Request.Builder()
                .url("https://alissl.ucdl.pp.uc.cn/fs08/2019/07/05/1/110_17e4089aa3a4b819b08069681a9de74b.apk")
                .get()
                .build();

        Call call = build.newCall(build1);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("tag", "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // liu
                ResponseBody body = response.body();
                InputStream inputStream = body.byteStream();
                long contentLength = body.contentLength();// 
                Log.i("Tag", "onResponse:  "+ contentLength /1024);
                File cacheDir = context.getCacheDir();// 
                File file = new File(cacheDir,"xxx.apk");// 
                FileOutputStream outputStream = new FileOutputStream(file);
                byte [] by=new byte[1024];
                int sum=0;
                int read = inputStream.read();
                while(read!=-1){//    
                    sum=sum+read;// 
                    float progies = sum*1.0f / contentLength;//  / 
                    Log.i("Tag", "onResponse: "+" "+ progies);
                    outputStream.write(by,0,read);// 
                    pb.setProgress((int) progies);// 
                    read = inputStream.read();


                }
                Toast.makeText(MainActivity.this, " ", Toast.LENGTH_SHORT).show();
                inputStream.close();
                outputStream.close();
                Log.i("tag", "onResponse: "+" "+file.length()/1024);
            }
        });

좋은 웹페이지 즐겨찾기