Introduce a OkHttp

OkHttp is an excellent network request framework. At present, the mainstream has replaced httpClient and HttpURLConnection.

OkHttp supports the connection of the same address to share the same socket, through the connection pool to reduce the response delay, GZIP compression, request caching and other advantages.

OkHttp has become the most common network request library for Android, but it doesn’t prevent the Java back end from learning it, so knowledge seekers here make common summaries

Making: github.com/square/okht…

Official documentation: square.github. IO /okhttp/

Two dependent

Latest version: 4.9.0

maven

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.6.0</version>
</dependency>
Copy the code

gradle

The compile 'com. Squareup. Okhttp3: okhttp: 3.6.0'Copy the code

Three GET request

Request step

  1. Get the OkHttpClient object
  2. Set request request
  3. Wrap the call
  4. Call asynchronously and set the callback function
 / * * *@AuthorLSC * <p>get request </p> *@Param [url]
     * @Return* /
    public void get(String url){
        // 1 Get the OkHttpClient object
        OkHttpClient client = new OkHttpClient();
        // 2 Sets the request
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        // 3 Encapsulates the call
        Call call = client.newCall(request);
        // 4 Call asynchronously and set the callback function
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if(response! =null && response.isSuccessful()){
                    // ...
                    // response.body().string();}}});// call synchronously, return Response, raise IO exception
        //Response response = call.execute();
    }
Copy the code

Four POST request

4.1 Form Form

  1. Get the OkHttpClient object
  2. Build the body parameter
  3. Build request
  4. Encapsulate Request as Call
  5. The asynchronous call
 / * * *@AuthorLSC * <p> POST request, form parameter </p> *@Param [url]
     * @Return* /
    public void postFormData(String url){
        // 1 Get the OkHttpClient object
        OkHttpClient client = new OkHttpClient();
        // 2 Build parameters
        FormBody formBody = new FormBody.Builder()
                .add("username"."admin")
                .add("password"."admin")
                .build();
        // 3 Build request
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        // 4 Encapsulate Request as Call
        Call call = client.newCall(request);
        // 5 Asynchronous call
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if(response! =null && response.isSuccessful()){
                    // ...}}}); }Copy the code

4.2 Json Parameter Format

  1. Get the OkHttpClient object
  2. Build parameters
  3. Build request
  4. Encapsulate Request as Call
  5. The asynchronous call
/ * * *@AuthorLSC * <p> POST request, JSON parameter </p> *@Param [url, json]
     * @Return* /
    public void postForJson(String url, String json){
        // 1 Get the OkHttpClient object
        OkHttpClient client = new OkHttpClient();
        // 2 Build parameters
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        // 3 Build request
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        // 4 Encapsulate Request as Call
        Call call = client.newCall(request);
        // 5 Asynchronous call
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if(response! =null && response.isSuccessful()){
                    // ...}}}); }Copy the code

If it is a JSON string, replace the request media type

 // 2 Build parameters
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), "{username:admin; password:admin}");
        // 3 Build request
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
Copy the code

4.3 Downloading Files

  1. Get the OkHttpClient object
  2. Build request
  3. The asynchronous call
  4. File download
/ * * *@AuthorLSC * <p> File download </p> *@ParamUrl Download address URL *@ParamTarget Download directory *@ParamTarget file name *@Return* /
    private void download(String url, String target, String fileName){
        // 1 Get the OkHttpClient object
        OkHttpClient client = new OkHttpClient();
        // 2 Build request
        Request request = new Request.Builder()
                .url(url)
                .build();
        // 3 Asynchronous call
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    // 4 File downloaddownlodefile(response, target,fileName); }}}); }private void downlodefile(Response response, String url, String fileName) {
        InputStream inputStream = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream outputStream = null;
        try {
            inputStream = response.body().byteStream();
            // File size
            long total = response.body().contentLength();
            File file = new File(url, fileName);
            outputStream = new FileOutputStream(file);
            long sum = 0;
            while((len = inputStream.read(buf)) ! = -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(inputStream ! =null)
                    inputStream.close();
                if(outputStream ! =null)
                    outputStream.close();
            } catch(IOException e) { e.printStackTrace(); }}}Copy the code

4.4 Uploading Files

  1. Get the OkHttpClient object
  2. The encapsulation parameters are in the form format and the media format is binary stream
  3. Encapsulates the request
  4. An asynchronous callback
/ * * *@AuthorLSC * <p> File upload </p> *@Param [url]
     * @Return* /
    public void upload(String url){
        File file = new File("C:/mydata/generator/test.txt");
        if(! file.exists()){ System.out.println("File does not exist");
        }else{
            // Get the OkHttpClient object
            OkHttpClient client = new OkHttpClient();
            // 2 Encapsulates arguments in form
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("username"."admin")
                    .addFormDataPart("password"."admin")
                    .addFormDataPart("file"."555.txt", RequestBody.create(MediaType.parse("application/octet-stream"), file))
                    .build();
            // 3 Encapsulates request
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            // 4 Asynchronous callback
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {}}); }}Copy the code

Public number knowledge seeker, welcome to pay attention to, get original PDF, face test set;