Android OkHttp Basic Usage Details

  • 2021-08-28 21:15:26
  • OfStack

The Android system provides two HTTP communication classes, HttpURLConnection And HttpClient .

Although Google recommends HttpURLConnection in most Android versions, this class is too difficult and weak compared with HttpClient.

OkHttp is a relatively mature solution. It is said that Android 4.4 source code can see that HttpURLConnection has been replaced by OkHttp. Therefore, we have more reason to believe that OkHttp is powerful.

Scope of use

OkHttp supports Android 2.3 and above.
For Java, JDK 1.7 or more.

Basic use

HTTP GET


OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder().url(url).build();
  Response response = client.newCall(request).execute();
  if (response.isSuccessful()) {
    return response.body().string();
  } else {
    throw new IOException("Unexpected code " + response);
  }
}

Request is the request for access in OkHttp, and Builder is the helper class. Response is the response in OkHttp.

Class Response:


public boolean isSuccessful()
Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

response.body() Return ResponseBody Class

string can be easily obtained


public final String string() throws IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8.
Throws:
IOException

Of course, you can also get the form of stream:


public final InputStream byteStream()

HTTP POST

POST Submit Json Data


public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
   .url(url)
   .post(body)
   .build();
  Response response = client.newCall(request).execute();
  f (response.isSuccessful()) {
    return response.body().string();
  } else {
    throw new IOException("Unexpected code " + response);
  }
}

Use Request Adj. post Method to submit the request body RequestBody

POST Submit key-value pairs

Most of the time, we need to transfer key-value pair data to the server through POST. OkHttp provides a very convenient way to do this.


OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {

  RequestBody formBody = new FormEncodingBuilder()
  .add("platform", "android")
  .add("name", "bug")
  .add("subject", "XXXXXXXXXXXXXXX")
  .build();

  Request request = new Request.Builder()
   .url(url)
   .post(body)
   .build();

  Response response = client.newCall(request).execute();
  if (response.isSuccessful()) {
    return response.body().string();
  } else {
    throw new IOException("Unexpected code " + response);
  }
}


Note:

The official OkHttp documentation does not recommend that we create multiple OkHttpClient, so use one globally. If necessary, you can use clone method and customize it. This will be mentioned in the advanced tutorial later. enqueue provides asynchronous methods for OkHttp, which are not mentioned in the introductory tutorial, but will be explained in the advanced tutorial later.

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import cn.wiz.sdk.constant.WizConstant;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response; 
 
public class OkHttpUtil {
  private static final OkHttpClient mOkHttpClient = new OkHttpClient();
  static{
    mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
  }
  /**
   *  This does not open asynchronous threads. 
   * @param request
   * @return
   * @throws IOException
   */
  public static Response execute(Request request) throws IOException{
    return mOkHttpClient.newCall(request).execute();
  }
  /**
   *  Open asynchronous threads to access the network 
   * @param request
   * @param responseCallback
   */
  public static void enqueue(Request request, Callback responseCallback){
    mOkHttpClient.newCall(request).enqueue(responseCallback);
  }
  /**
   *  Open asynchronous threads to access the network ,  And doesn't care about returning results (implementing null callback ) 
   * @param request
   */
  public static void enqueue(Request request){
    mOkHttpClient.newCall(request).enqueue(new Callback() {
      
      @Override
      public void onResponse(Response arg0) throws IOException {
        
      }
      
      @Override
      public void onFailure(Request arg0, IOException arg1) {
        
      }
    });
  }
  public static String getStringFromServer(String url) throws IOException{
    Request request = new Request.Builder().url(url).build();
    Response response = execute(request);
    if (response.isSuccessful()) {
      String responseUrl = response.body().string();
      return responseUrl;
    } else {
      throw new IOException("Unexpected code " + response);
    }
  }
  private static final String CHARSET_NAME = "UTF-8";
  /**
   *  Here, we use HttpClinet Adj. API . Just for convenience 
   * @param params
   * @return
   */
  public static String formatParams(List<BasicNameValuePair> params){
    return URLEncodedUtils.format(params, CHARSET_NAME);
  }
  /**
   *  For HttpGet  Adj.  url  Conveniently add multiple name value  Parameter. 
   * @param url
   * @param params
   * @return
   */
  public static String attachHttpGetParams(String url, List<BasicNameValuePair> params){
    return url + "?" + formatParams(params);
  }
  /**
   *  For HttpGet  Adj.  url  Convenient addition 1 A name value  Parameter. 
   * @param url
   * @param name
   * @param value
   * @return
   */
  public static String attachHttpGetParam(String url, String name, String value){
    return url + "?" + name + "=" + value;
  }
}

Summarize

Through the above example, we can find that OkHttp is very convenient to use in many cases, and many codes are repeated, so the following tool classes are specially sorted out.


Related articles: