java Learning Diary 8: The implementation of the file upload tool class and the server send pictures to the client Sleepat

2023-01-12   ES  

Here is the framework shared by the great god of Hongyang:https://github.com/hongyangAndroid/okhttputils

and the blog of Hongyang Great God:https://blog.csdn.net/lmj623565791/article/details/47911083

Import before use:

implementation 'com.zhy:okhttputils:2.6.2'

How to use:

Get request

String url = "http://www.csdn.net/";
OkHttpUtils
    .get()
    .url(url)
    .addParams("username", "hyman")
    .addParams("password", "123")
    .build()
    .execute(new StringCallback()
	        {
	            @Override
	            public void onError(Request request, Exception e)
	            {
	                
	            }
	
	            @Override
	            public void onResponse(String response)
	            {
	
	            }
	        });

 

POST request

 OkHttpUtils
    .post()
    .url(url)
    .addParams("username", "hyman")
    .addParams("password", "123")
    .build()
    .execute(callback);

 

Post JSON

  OkHttpUtils
    .postString()
    .url(url)
    .content(new Gson().toJson(new User("zhy", "123")))
     .mediaType(MediaType.parse("application/json; charset=utf-8"))
    .build()
    .execute(new MyStringCallback());

Submit a GSON string to the server side. Note: When passing JSON, do not set ContentType through addheader to use.mediaType(MediaType.parse("application/json; charset=utf-8")).。

 

Post File

 OkHttpUtils
	.postFile()
	.url(url)
	.file(file)
	.build()
	.execute(new MyStringCallback());

Send the file as a request body and send it to the server.

 

POST forms Upload file

OkHttpUtils.post()//
    .addFile("mFile", "messenger_01.png", file)//
    .addFile("mFile", "test1.txt", file2)//
    .url(url)
    .params(params)//
    .headers(headers)//
    .build()//
    .execute(new MyStringCallback());

Support a single multiple files,

The first parameter of theaddFileis the key of the file, that is, in the category form<input type="file" name="mFile"/>Name attribute.

 

Custom callback

Currently containingStringCallBack,FileCallBack,BitmapCallback, you can customize the callback according to your own needs, for example, want to call the User object:

public abstract class UserCallback extends Callback<User>
{
    @Override
    public User parseNetworkResponse(Response response) throws IOException
    {
        String string = response.body().string();
        User user = new Gson().fromJson(string, User.class);
        return user;
    }
}

 OkHttpUtils
    .get()//
    .url(url)//
    .addParams("username", "hyman")//
    .addParams("password", "123")//
    .build()//
    .execute(new UserCallback()
    {
        @Override
        public void onError(Request request, Exception e)
        {
            mTv.setText("onError:" + e.getMessage());
        }

        @Override
        public void onResponse(User response)
        {
            mTv.setText("onResponse:" + response.username);
        }
    });

parseNetworkResponse Return the response analysis. This method runs in the sub -thread, so you can perform any time -consuming operation. See SAMPLE in detail.

 

download file

 OkHttpUtils//
	.get()//
	.url(url)//
	.build()//
	.execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "gson-2.2.1.jar")//
	{
	    @Override
	    public void inProgress(float progress)
	    {
	        mProgressBar.setProgress((int) (100 * progress));
	    }
	
	    @Override
	    public void onError(Request request, Exception e)
	    {
	        Log.e(TAG, "onError :" + e.getMessage());
	    }
	
	    @Override
	    public void onResponse(File file)
	    {
	        Log.e(TAG, "onResponse :" + file.getAbsolutePath());
	    }
	});

Note that the download file can be usedFileCallback, the folder and file name that needs to be preserved in the file.

 

Display picture

 OkHttpUtils
    .get()//
    .url(url)//
    .build()//
    .execute(new BitmapCallback()
    {
        @Override
        public void onError(Request request, Exception e)
        {
            mTv.setText("onError:" + e.getMessage());
        }

        @Override
        public void onResponse(Bitmap bitmap)
        {
            mImageView.setImageBitmap(bitmap);
        }
    });

Show the picture, the callback is passed inBitmapCallback

 

Upload download progress display

new Callback<T>()
{
    //...
    @Override
    public void inProgress(float progress)
    {
       //use progress: 0 ~ 1
    }
}

CallBack’s callbacksinProgress method, just write directly.

 

HEAD、DELETE、PUT、PATCH

OkHttpUtils
     .put()//also can use delete() ,head() , patch()
     .requestBody(RequestBody.create(null, "may be something"))//
     .build()//
     .execute(new MyStringCallback());

If requestbody is required, for example: put, patch, the constructor is passed in.

 

Synchronous request

The

 Response response = OkHttpUtils
    .get()//
    .url(url)//
    .tag(this)//
    .build()//
    .execute();

Execute method is not passed into the callback as a synchronous request, and returns Response.

 

Cancel a single request

 RequestCall call = OkHttpUtils.get().url(url).build();
 call.cancel();
 

 

Cancel the request according to TAG

At present, the last parameter is added to the support methodObject tag, cancellation is passed OkHttpUtils.cancelTag(tag)execute.

For example: in Activity, when the Activity destroys the cancellation request:

okhttputils 
     .get () // 
     .url (url) // 
     .tag (this) // 
     .build () // 

 @Override 
 Protected void onDestroy () 
 {{ 
     Super.ondestroy (); 
     // You can cancel the same tag 
     Okhttputils.canceltag (this); // Cancel the request with Activity.this as a TAG request 
 }

For example, all requests on the current Activity page are based on the Activity object as a TAG, which can be canceled uniformly in ONDestory.

Several websites:

OKHTTP framework:https://github.com/square/okhttp

OK-GO framework:https://github.com/jeasonlzy/okhttp-OkGo

Jiugongge control:https://github.com/jeasonlzy/NineGridView

Picture selection framework:https://github.com/jeasonlzy/ImagePicker

source

Related Posts

[SpringCloud] Fenchley & Greenwich skeleton construction (1)

IOS development Homekit (2) lu

java experiment 9 rectangular definition and packaging

Commonjs/ES6/AMD module

java Learning Diary 8: The implementation of the file upload tool class and the server send pictures to the client Sleepat

Random Posts

Find the neutral neutral and the combination IT for the given number

qt configuration system new project function

Talk about Vue component welkin

form.submit ()

date and time type