Learning and simple use of okhttp

Official address: https://github.com/square/okhttp/
An open source project for processing network requests, it is the most popular lightweight framework on Android
<dependency>
     <groupId>com.squareup.okhttp3</groupId>
     <artifactId>okhttp</artifactId>
     <version>3.10.0</version>
  </dependency>
    


Simple test okhttp Get request
package com.sb.okhttp.okhttp;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Test {
	// Create OkhttpClient object
	OkHttpClient client = new OkHttpClient();
	
	/**
	 * okhttp get synchronous request
	 */
	public void testGet(String url) {
		Request request = new Request.Builder().get().url(url) // request address
				.build();// Create Request object,
		Response response = null;
		try {
			// Execute the request and get the Response object
			response = client.newCall(request).execute();
		} catch (IOException e) {
			e.printStackTrace ();
		}
		if (null != response) {
			if (response.isSuccessful()) {// The request is successful
				System.out.println(response.code());// status code
				System.out.println(response.message());// message
				try {
					String res = response.body().string();
					System.out.println(res);
				} catch (IOException e) {
					e.printStackTrace ();
				}
			} else {
				System.out.println("Request failed");
			}
		} else {
			System.out.println("Request failed");
		}
	}
	
	/**
	 * okhttp get asynchronous request
	 */
	public void asynchronousGet(String url){
		Request request = new Request.Builder().get().url(url) // request address
				.build();// Create Request object
		client.newCall(request).enqueue(new Callback() {
			public void onResponse(Call arg0, Response response) throws IOException {
				//Note: the onResponse callback will be executed in the child thread, not the main thread
				if (response.isSuccessful()) {// The request is successful
					System.out.println(response.code());// status code
					System.out.println(response.message());// message
					try {
						String res = response.body().string();
						System.out.println(res);
					} catch (IOException e) {
						e.printStackTrace ();
					}
				} else {
					System.out.println("Request failed");
				}
			}
			//Note: the onFailure callback will be executed in the child thread, not the main thread
			public void onFailure(Call arg0, IOException arg1) {
				System.out.println("Request failed");
			}
			
		});
	}
	
	public static void main(String[] args) {
		Test t = new Test();
		String url = "http://www.baidu.com";
		//t.testGet(url);
		t.asynchronousGet(url);
	}
}



Test okhttp Post request
package com.sb.okhttp.okhttp;

import java.io.File;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TestPost {
	//data type json
	public static final MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
	//Data type File
	public static final MediaType mediaType_file = MediaType.parse("File/*");
	
	OkHttpClient client = new OkHttpClient();
	
	/**
	 * Post submit Json data
	 * @param url submitted address
	 * @param json submit json data
	 * @return returns the result data returned after post
	 */
	public String postJson(String url,String json){
		RequestBody body = RequestBody.create(mediaType,json);
		Request request = new Request.Builder().url(url).post(body).build();
		Response response = null;
		try {
			response = client.newCall(request).execute();
			if(null!=response){
				if(response.isSuccessful()){
					return response.body().string();
				}
			}
		} catch (IOException e) {
			e.printStackTrace ();
		}
		return null;
	}
	
	/**
	 * okhttp simulate form submission
	 * @param url post address
	 */
	public void postKeyValue(String url ){
		FormBody.Builder formBody = new FormBody.Builder();//Create form request body
		formBody.add("name","zbb");
		formBody.add("age","26");
		Request request = new Request.Builder() //Create a request object
		                  .url(url)
		                  .post(formBody.build()) //Pass the request body
		                  .build();
		client.newCall(request).enqueue(new Callback() {
			public void onResponse(Call call, Response res) throws IOException {
				//Callback after the request is successfully responded
				if(res.isSuccessful()){
					String result = res.body().string();
					System.out.println(result);
				}
			}
			
			public void onFailure(Call call, IOException arg1) {
				//Callback after the request fails
				//.... code omitted here
			}
		});
	}
	
	/**
	 * okhttp upload File object
	 * @param filePath file path
	 * @param url the address to submit to
	 */
	public void postFile(String filePath,String url){
		File file = new File(filePath);
		RequestBody body = RequestBody.create(mediaType_file,file);
		Request request = new Request.Builder()
							.url(url)
							.post(body)
							.build();
	    client.newCall(request).enqueue(new Callback() {
			public void onResponse(Call arg0, Response arg1) throws IOException {
				//Callback after the request is successfully responded
				//.....
			}
			
			public void onFailure(Call arg0, IOException arg1) {
				//Callback after the request fails
				//.....
			}
		});
	}
	
	/**
	 * okhttp post both pass form parameters and submit File
	 * @param file file object
	 * @param url the address to submit to
	 */
	public void postMultipartBody(File file,String url){
		MultipartBody body = new MultipartBody.Builder()
		                     .setType(MultipartBody.FORM)
		                     .addFormDataPart("name","zbb")
		                     .addFormDataPart("age","26")
		                     .addFormDataPart("f",file.getName(),
		                    		 RequestBody.create(mediaType_file,file))
		                     .build();
		Request request = new Request.Builder()
		                  .url(url)
		                  .post(body)
		                  .build();
		client.newCall(request).enqueue(new Callback() {
			public void onResponse(Call arg0, Response arg1) throws IOException {
				//Callback after the request is successfully responded
				//.....
			}
			
			public void onFailure(Call arg0, IOException arg1) {
				//Callback after the request fails
				//.....
			}
		});
	}
	
	public static void main(String[] args) {
		
	}
    
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326267943&siteId=291194637