General overview
Simple create A GET request POST request Download (display progress) Upload (display progress) OthersCopy the code
OkHttp is an open source project that handles web requests; Android lightweight framework; Used to replace HttpUrlConnection and Apache HttpClient;
The preparatory work
Add the dependent
/ / network request OkHttp3 implementation 'com. Squareup. OkHttp3: okhttp: 4.3.1'Copy the code
Setting Network Permissions
<uses-permission android:name="android.permission.INTERNET" />
Copy the code
For mobile phones with API level 28 or higher, an error message is displayed during HTTP requests (non-HTTPS requests) and no data is requested.
CLEARTEXT communication to www.baidu.com not permitted by network security policy
Copy the code
Need in the application of AndroidManifest set android: usesCleartextTraffic = “true”
create
Okhttp provides both synchronous and asynchronous request methods, which are Not very different. When a synchronous request is made, the thread is blocked during the request. It is Not recommended to run it in the main thread.
Simple creation in four steps
Create a Request object (OkHttpClient); create a Request object (OkHttpClient); create a Call object (call.enqueue()); Call call.execute () to perform the synchronization requestCopy the code
An asynchronous request
OkHttpClient client = new OkHttpClient(); // instantiate the OkHttpClient object
Request request = new Request.Builder() // Create the Builder mode for the Request object
.url("http://www.baidu.com") // Set the url to access
//.get() // Set to GET request The default is GET request and can be ignored
.build(); // Create a Request object
Call call = client.newCall(request); // Construct a Call object from the request object
call.enqueue(new Callback() { // Call the call enqueue() to make an asynchronous request
@Override
public void onFailure(Call call, IOException e) {
LLDB error message () : LLDB error message (
Log.d("onFailure"."onFailure: "+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// Successful callback, where we can get the data returned by the server
Log.d("onResponse"."onResponse: "+response.body().string()); }});Copy the code
A synchronous request
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.get()
.build();
Call call = client.newCall(request);
Response response = null;
try {
response = call .execute();Execute () of the call is blocked during the request process. It is recommended to write to the child thread
Log.d("onResponse"."onResponse: "+response.body().string());
} catch (IOException e) {
e.printStackTrace();
Log.d("onFailure"."onFailure: "+e.getMessage());
}
Copy the code
The onResponse callback has an argument that response is the response data. If the data returned is a string, you can get it from Response.body ().string(). If the data returned is a binary byte array, Response.body ().bytes() If the data returned is an inputStream, it can be response.body().bytestream ()Copy the code
Suspend the request
Abort by calling call cancel() to stop calling call.cancel();
Detailed introduction
OkHttp supports PUT, DELETE, POST, and GET requests. The following files are uploaded and downloaded using asynchronous requests
A GET request
GET requests are relatively simple, consisting of the four simple steps above
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("")
.get()
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {}@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {}});Copy the code
A POST request
POST requests support simple POST requests (submit forms) for files, streams, strings, forms, etc.
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()// Create form
.add("key"."value") // Pass in the data to commit
.add("key"."value") // Pass in the data to commit
.build(); // Create the request body
Request request = new Request.Builder()
.url("") // Set the url for submitting data
.post(requestBody) // Set it to POST, passing in the request body
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() { // Asynchronous request
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {}@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {}});Copy the code
Download (save to local)
A GET request or a POST request simply converts the returned data to a stream (response.body().bytestream ()) and saves it locally via InputStream() and OutputStream().
Simple download request (example)
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download" +
"&ie=utf8&fr=result&url=http%3A%2F%2Fc.hiphotos.baidu.com%2Fzhidao%2" +
"Fpic%2Fitem%2Fd009b3de9c82d1587e249850820a19d8bd3e42a9.jpg&thumburl=" +
"http%3A%2F%2Fimg1.imgtn.bdimg.com%2Fit%2Fu%3D3675415932%2C4054970339%26" +
"fm%3D26%26gp%3D0.jpg") // Picture on Baidu
.get()
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d("onFailure"."onFailure: " + e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String path = Environment.getExternalStorageDirectory().getPath()+"/Download";// File path, root directory Download directory
File file = new File(path,"image.jpg");// Set the path and name of the file
InputStream is = response.body().byteStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(new File(path));
byte[] bytes = new byte[1024];
int len;
Log.d("onResponse"."OnResponse: started");
while((len=is.read(bytes))! = -1){
fos.write(bytes,0,len);
}
fos.flush();
Log.d("onResponse"."OnResponse: end"); is.close(); bis.close(); fos.close(); }});Copy the code
The preparatory work
Permission Obtain Indicates the access permission of the SD card
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Copy the code
In Android 6.0, Google introduced the permission application mechanism, which requires dynamic permission application and user authorization to use dangerous permissions. Access permissions are hazard permissions.
How do I get it dynamically? A utility class is provided for dynamic authorization
public class PermissionUtil {
public static String READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE; // Memory read
public static String WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE; // Memory write
public static void getPermissions(Activity activity, String... permission) {
List<String> permissions = new ArrayList<>();
// Apply for dynamic permission here
// Check whether the system is greater than or equal to Android 6.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for(int i=0; i<permission.length; i++){int request = ContextCompat.checkSelfPermission(activity, permission[i]);
// Check whether the permission is not obtained
if(request ! = PackageManager.PERMISSION_GRANTED) permissions.add(permission[i]); }if (permissions.size()>0) {// Lack of permission, apply for permission
// Current context; An array of permissions; A unique request code (16 digits from 0 to 65535)
ActivityCompat.requestPermissions(activity, permissions.toArray(new String[permissions.size()]), 0XFF);
} else {
// Permission permission is fully authorized}}else {
// No dynamic authorization is required below API 23}}}Copy the code
Used in MainActivity onCreate() for dynamic authorization
PermissionUtil.getPermissions(this, PermissionUtil.READ_EXTERNAL_STORAGE, PermissionUtil.WRITE_EXTERNAL_STORAGE);
Copy the code
Display download progress
There are two ways to display the download progress:
- Get it in real time in the onResponse callback
- Proxy the network response ResponseBody
The first is relatively simple (currently available only and may not work when combined with other frameworks, e.g. Retrofit+OkHttp3+RxJava2 will not work when combined due to Retrofit)
The second is a bit more complicated, involving interceptors and directly pasting code
Second: proxy activity_main for ResponseBody
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progressBar"
style="? android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Download" />
</LinearLayout>
Copy the code
MainActivity
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Android 6.0 and above requires dynamic application. The PermissionUtil tool has been posted above
PermissionUtil.getPermissions(this, PermissionUtil.READ_EXTERNAL_STORAGE, PermissionUtil.WRITE_EXTERNAL_STORAGE);
progressBar = findViewById(R.id.progressBar);
// Set the button click event
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
download();// Click to download}}); }public void download(a){
String path = Environment.getExternalStorageDirectory().getPath() + "/Download/qq.exe";// Save path and file name
String url = "https://qd.myapp.com/myapp/qqteam/pcqq/PCQQ2020.exe";// Here is the QQPC version download address, the file is large
// Set the download path and url to start the download
OkHttpHelper.getInstance().setDownloadUrl(url).startDownload(path,new OkHttpHelper.DownloadCallback() {
@Override
public void start(final long max) {
// This is a child thread and needs to go back to the main thread to update the UI
progressBar.post(new Runnable() {
@Override
public void run(a) {
Toast.makeText(MainActivity.this."Start downloading", Toast.LENGTH_SHORT).show();
progressBar.setMax((int) max); }}); }@Override
public void loading(final long progress) {
progressBar.post(new Runnable() {
@Override
public void run(a) {
progressBar.setProgress((int) progress); }}); }@Override
public void complete(String msg) {}@Override
public void fail(String message) {}}); }}Copy the code
OkHttpHelper
public class OkHttpHelper {
private OkHttpClient client;
private Request request;
private static OkHttpHelper instance = null;
private OkHttpHelper(a) {
initOkHttp();/ / initialization
}
static OkHttpHelper getInstance(a) {// Singleton mode
if (instance == null) {
synchronized (OkHttpHelper.class) {
if (instance == null) {
instance = newOkHttpHelper(); }}}return instance;
}
private void initOkHttp(a) {
client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
}
// Set GET request, set download url
OkHttpHelper setDownloadUrl(String url) {
request = new Request.Builder()
.url(url)
//. Header ("RANGE","")//
.get()
.build();
return this;
}
// Set the download path and start the download
public void startDownload(final String path,final DownloadCallback callback) {
if (client == null) {
initOkHttp();
}
OkHttpClient okHttpClient = client.newBuilder().addInterceptor(new MyInterceptor(callback)).build();Insert a custom MyInterceptor() interceptor
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
callback.fail(e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
download(response,path);
callback.complete("Complete"); }}); }// Create MyInterceptor class to implement Interceptor
static class MyInterceptor implements Interceptor {
DownloadCallback callback;
public MyInterceptor(DownloadCallback callback) {
super(a);this.callback = callback;
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response.newBuilder().body(newMyResponseBody(response,callback)).build(); }}// Create MyResponseBody and inherit from ResponseBody
static class MyResponseBody extends ResponseBody {
Response response;
DownloadCallback callback;
MyResponseBody(Response response,DownloadCallback callback) {
super(a);this.response = response;
this.callback = callback;
}
@Override
public long contentLength(a) {
// Get the total number of bytes of the file
callback.start(response.body().contentLength());
return response.body().contentLength();
}
@Nullable
@Override
public MediaType contentType(a) {
// Can get the type of file
return response.body().contentType();
}
@NotNull
@Override
public BufferedSource source(a) {
contentLength();
contentType();
// Get file resources
return Okio.buffer(new ForwardingSource(response.body().source()) {
long bytesLength=0;
@Override
public long read(@NotNull Buffer sink, long byteCount) throws IOException {
// Get the download progress
final long bytesRead = super.read(sink, byteCount);
bytesLength += bytesRead;
callback.loading(bytesLength);
returnbytesRead; }}); }}/ / note: the three interfaces in the MyResponseBody contentLength, contentType, source, call on their own will not follow, need artificial passive implementation;
InputStream is = Response.body ().bytestream (); "Will be called;
// Then we call the contentLength(),contentType() methods ourselves,
InputStream is = response.body().bytestream (); Add two lines of response.body().contentLength(); ,response.body().contentType();
// Download, perform download, save
public static void download(Response response,String path) throws IOException {
//response.body().contentLength();
//response.body().contentType();
InputStream is = response.body().byteStream();// Get the resource and turn it into a byte stream
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(new File(path));// Set the location and file to save
byte[] bytes = new byte[1024];
int len;
while((len = is.read(bytes)) ! = -1) {
fos.write(bytes, 0, len);/ / save
}
fos.flush();
is.close();
bis.close();
fos.close();
}
// Some necessary interfaces
public interface DownloadCallback { // Various interfaces required for downloading
// Start downloading
void start(long max); // Total number of bytes of the incoming file
// Downloading
void loading(long progress); // Pass in the number of bytes downloaded
// Download complete
void complete(String msg); // Pass a success message
// The request failed
void fail( String message); // An error message was passed in}}Copy the code
MyResponseBody (); MyResponseBody (); MyResponseBody (); InputStream is = Response.body ().bytestream (); “Will be called; 3. Then we call contentLength() and contentType() ourselves; 4, Or we can add two lines of response.body().contentLength() to the Download method; ,response.body().contentType(); , will also be executed.
The first is to get the modification OkHttpHelper in real time in the onResponse callback
public class OkHttpHelper {
private static OkHttpHelper instance = null;
private OkHttpClient client;
private Request request;
private OkHttpHelper(a) {
initOkHttp();/ / initialization
}
static OkHttpHelper getInstance(a) {// Singleton mode
if (instance == null) {
synchronized (OkHttpHelper.class) {
if (instance == null) {
instance = newOkHttpHelper(); }}}return instance;
}
OkHttpHelper setDownloadUrl(String url) {
request = new Request.Builder()
.url(url)
//. Header ("RANGE","")//
.get()
.build();
return this;
}
private void initOkHttp(a) {
client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
}
void startDownload(final String path, final DownloadCallback callback) {
if (client == null) {
initOkHttp();
}
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
callback.fail(e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
downlaod(response, path, callback);
callback.complete("Complete"); }}); }public static void downlaod(Response response, String path, DownloadCallback callback) throws IOException {
long max = response.body().contentLength();
callback.start(max);
InputStream is = response.body().byteStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(new File(path));
byte[] bytes = new byte[1024];
int len;
long length = 0;// Record the number of bytes downloaded
while((len = is.read(bytes)) ! = -1) {
length += len;
fos.write(bytes, 0, len);
callback.loading(length);
}
fos.flush();
is.close();
bis.close();
fos.close();
}
public interface DownloadCallback {
// Start downloading
void start(long max);// Total number of bytes of the incoming file
// Downloading
void loading(long progress);// Pass in the number of bytes downloaded
// Download complete
void complete(String msg);
// The request failed
void fail(String message); }}Copy the code
upload
File upload
Parse ("text/plain; Charset = UTF-8 ") text/ HTML HTML text/plain Text Document Text/XML XML image/ GIF GIF image/ JPEG JPG image/ PNG PNG Application /xhtml-xml XHTML application/json json application/ PDF PDF application/msword Word Document Application/OCtet-stream Binary streamCopy the code
File upload (simple example)
OkHttpClient client = new OkHttpClient();/ / instantiate
// Get the uploaded file
File file = new File(Environment.getExternalStorageDirectory(),"/Download/qq.exe");
// Set the upload type
MediaType type = MediaType.parse("");
// Set the request body
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(""."")
// Put the file type and file into the request body
.addFormDataPart(""."",RequestBody.create(file, type))
.build();
//RequestBody body = RequestBody.create(file, type);
// Set the url to upload (to support upload url) into the request body
Request request = new Request.Builder()
.url("")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {// Asynchronous request
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {}@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {}});Copy the code
Classes and methods involved
new RequestBody(); RequestBody.create(byte[]); RequestBody.create(File, MediaType); Requestbody.create (byte[], MediaType); // Use requestBody.create (String, MediaType) to upload binary bytes; // Use requestBody.create (ByteString, MediaType) to upload text; Requestbody.create (byte[], MediaType,int offset); // offset Uploads requestBody. create(byte[], MediaType,int offset,int byteCount); // offset, byteCount starts at offset, and ends at offset. Upload new MultipartBody(); new MultipartBody.Builder(); builder.setType(MediaType); //MultipartBody.FORM sets the type to FORM Builder. addFormDataPart(String, String); // Add data Builder.addFormDatApart (String, String, RequestBody); // Add the uploaded file and the necessary information builder.build(); // Return RequestBody new MediaType(); MediaType.parse(String); // Set the type of file to uploadCopy the code
Upload monitor (display upload progress)
The web request RequestBody is proxyed
I’m going to go straight to the code
Activity_main ditto
MainActivity
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PermissionUtil.getPermissions(this, PermissionUtil.READ_EXTERNAL_STORAGE, PermissionUtil.WRITE_EXTERNAL_STORAGE);
progressBar = findViewById(R.id.progressBar);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { upload(); }}); }public void upload(a) {
Map<String, String> map = new HashMap<>();
String path = Environment.getExternalStorageDirectory().getPath() + "/Download/123.jpg";
File file = new File(path);
String url = "";
OkHttpHelper.getInstance().setUploadUrl(url).startUpload(map, file, new OkHttpHelper.UploadCallback() {
@Override
public void start(long max) {}@Override
public void loading(long progress) {}@Override
public void complete(String msg) {}@Override
public void fail(String message) {}}); }}Copy the code
OkHttpHelper
public class OkHttpHelper {
private static OkHttpHelper instance = null;
private OkHttpClient client;
private Request request;
private OkHttpHelper(a) {
initOkHttp();/ / initialization
}
static OkHttpHelper getInstance(a) {// Singleton mode
if (instance == null) {
synchronized (OkHttpHelper.class) {
if (instance == null) {
instance = newOkHttpHelper(); }}}return instance;
}
public OkHttpHelper setUploadUrl(String url) {
request = new Request.Builder()
.url(url)
.build();
return this;
}
public void startUpload(Map<String, String> map, File file,final UploadCallback callback) {
// Refactor the Request body passed in.post()
Request request = this.request.newBuilder().post(new MyRequestBody(setUploadBody(map, file),callback)).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
callback.fail(e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { callback.complete(response.body().string()); }}); }private static class MyRequestBody extends RequestBody {
RequestBody body = null;
UploadCallback callback;
public MyRequestBody(MultipartBody multipartBody, UploadCallback callback) {
super(a); body = multipartBody;this.callback = callback;
}
@Nullable
@Override
public MediaType contentType(a) {
return body.contentType();
}
@Override
public long contentLength(a) throws IOException {
callback.start(body.contentLength());
return body.contentLength();
}
@Override
public void writeTo(@NotNull BufferedSink bufferedSink) throws IOException {
/ / packaging
Sink sk = sink(bufferedSink);
bufferedSink = Okio.buffer(sk);
/ / write
body.writeTo(bufferedSink);
// You must call flush, or the last bit of data may not be written
bufferedSink.flush();
}
/** * write, callback progress interface **@param sink Sink
* @return Sink
*/
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
// Get the upload progressbytesWritten += byteCount; callback.loading(bytesWritten); }}; }}// Package the data to be uploaded
private MultipartBody setUploadBody(Map<String, String> map, File file) {
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
RequestBody fileBody = RequestBody.create(file, MediaType.parse("image/png"));
if(map ! =null && map.size() > 0) {
for (String key : map.keySet()) {
String value = map.get(key);
if(value ! =null) { builder.addFormDataPart(key, value); }}}return builder.addFormDataPart("file"."fileName", fileBody).build();
}
public interface UploadCallback {
// Start uploading
void start(long max);// Total number of bytes of the incoming file
// Uploading
void loading(long progress);// Pass in the number of bytes downloaded
// Upload complete
void complete(String msg);
// The request failed
void fail(String message); }}Copy the code
other
The interceptor
Interceptors are a powerful mechanism for monitoring, overriding, and retrying calls.
// This is the simplest interceptor
static class MyInterceptor implements Interceptor {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
return response;
//return chain.proceed(chain.request());}}// How to use it
OkHttpHelper client = new OkHttpClient.Builder()
.addInterceptor(new MyInterceptor()) // Register the application interceptor
.addNetworkInterceptor()// Register a network interceptor
.build();
Copy the code
Calling chain.proceed(request) is a key part of every interceptor implementation. This simple approach is where all the HTTP work takes place, generating a response to satisfy the request. If chain.proceed(request) is called multiple times, the previous response body must be closed. (Official translation)
Apply interceptors without worrying about intermediate responses, such as redirects and retries. Even if an HTTP response is provided from the cache, it is always called once. Adhere to the original intent of the application. Do not care about OkHttp injected headers, such as if-none-match. Allows short-circuiting instead of chain.proceed (). Allow retry and call chain.proceed () multiple times.
The network interceptor can operate on intermediate responses such as redirects and retries. Will not be called for cache responses that short-circuit the network. Observe the data as if it were transmitted over a network. Access Connection with a request.
Retry and redirect the interceptor RetryAndFollowUpInterceptor bridge interceptor BridgeInterceptor cache interceptor CacheInterceptor connection interceptor interceptor ConnectInterceptor, speaking, reading and writing CallServerInterceptor
LoggerInterceptor Interceptor prints the header information of network requests. It prints the URL cache of the request :cache-control, max-age= XXX
Classes and methods that may be involved
new Cache(File,long,FileSystem); New Cache(File,long); // Set the number of caches using new OkHttpClient(); newBuilder(); New okHttpClient.builder () Builder.connectTimeout (Long, TimeUnit); //long sets the connection timeout duration, TimeUnit sets the TimeUnit (hour, minute, second) builder.readTimeout(long, TimeUnit); //long sets the read timeout duration, builder.writeTimeout(long, TimeUnit); //long sets the write timeout period, builder.addinterceptor (Interceptor); // Set interceptor builder.cache(cache); // Set the cache builder.build(); // return OkHttpClient new MediaType(); MediaType.parse(String); new RequestBody(); RequestBody.create(byte[]); RequestBody.create(File, MediaType); Requestbody.create (byte[], MediaType); // Use requestBody.create (String, MediaType) to upload binary bytes; // Use requestBody.create (ByteString, MediaType) to upload text; Requestbody.create (byte[], MediaType,int offset); // offset Uploads requestBody. create(byte[], MediaType,int offset,int byteCount); // offset, byteCount starts at offset, ends at offset, uploads new FormBody(); // Set the form new formBody.builder (); formBody.add(String, String); formBody.build(); // Return RequestBody new MultipartBody(); new MultipartBody.Builder(); builder.setType(MediaType); //MultipartBody.FORM sets the type to FORM Builder. addFormDataPart(String, String); // Add data Builder.addFormDatApart (String, String, RequestBody); builder.build(); // Return RequestBody new Request(); new Request.Builder(); builder.url(String); builder.post(RequestBody); builder.addHeader(String, String); Method (String, RequestBody) // set request type (GET,POST) and RequestBody builder.build(); new Call(); call.execute(); Call.enqueue (Callback); // Call call.cancel() asynchronously; // Request to terminate new Response(); response.body(); response.body().string(); response.body().bytes(); response.body().byteStream();Copy the code
See here, if you feel good can like, encourage me to encourage me