Home > Java > javaTutorial > body text

Detailed explanation of the usage and examples of OkHttp in java

怪我咯
Release: 2017-07-02 10:29:31
Original
2097 people have browsed it

This article mainly introduces the usage methods and examples of OkHttp in java. Friends who need it can refer to the following

The usage methods and examples of OkHttp in java

Overview

Prepare to study Retrofit, and it relies on OkHttp, so use OkHttp first, without delving into the source code, just explore how to use it. I will check the source code again when I have the opportunity.

Before proceeding, you first need 2 jar packages, one of which is the okHttp jar package, which can be downloaded from github, and the other is its dependency package. This is very critical. Without it, the project cannot run.

Two ways of OkHttp request

It is not difficult to guess that when it comes to network requests, there are only two ways, one is to use callbacks, and the other is The first is to start child thread execution.

The first one: start the sub-thread for execution

OkHttpClient client = new OkHttpClient(); 
Request build = new Request.Builder().url(url).build(); 
try { 
<span style="white-space:pre">  </span>Response execute = client.newCall(build).execute(); 
  if(execute.isSuccessful()){ 
    System.out.println("wisely aaa"); 
  } else { 
    System.out.println("wisely bbb"); 
  } 
} catch (IOException e) { 
  e.printStackTrace(); 
}
Copy after login

The second one: use callbacks, I personally like to use this the best. (PS: I feel that I am too young and too simple!! I originally thought that the callback method was in the main thread, but it turned out that it was a sub-thread, a sub-thread....)

OkHttpClient client = new OkHttpClient(); 
Request build = new Request.Builder().url(url).build(); 
client.newCall(build).enqueue(new Callback() { 
 
  @Override 
  public void onResponse(Response arg0) throws IOException { 
    System.out.println("wisely  success"); 
  } 
 
  @Override 
  public void onFailure(Request arg0, IOException arg1) { 
    System.out.println("wisely  failure"); 
  } 
});
Copy after login

OkHttp's get request

1. Getpicture

OkHttpClient client = new OkHttpClient(); 
     
Request build = new Request.Builder().url(url).build(); 
client.newCall(build).enqueue(new Callback() { 
       
  @Override 
  public void onResponse(Response response) throws IOException { 
//   byte[] bytes = response.body().bytes(); 
    InputStream is = response.body().byteStream(); 
    Options options = new BitmapFactory.Options(); 
    options.inSampleSize = 8; 
//   Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,options); 
    Bitmap bitmap = BitmapFactory.decodeStream(is, null, options); 
    Message msg = handler.obtainMessage(); 
    msg.obj = bitmap; 
    handler.sendMessage(msg); 
  } 
     
  @Override 
  public void onFailure(Request arg0, IOException arg1) { 
    System.out.println("wisely fail:"+arg1.getCause().getMessage()); 
  } 
});
Copy after login

only writes the key code and does not write the handler Related code.

There are two ways to obtain network images, 1 is to obtain the bytearray, and 2 is to obtain the input stream. Note that onResponse is in the child thread...

OkHttp'spost request

Compared with the get request, post There are slightly more categories requested.

1. The first is the most commonly used form submission.

OkHttpClient client = new OkHttpClient(); 
 
RequestBody body = new FormEncodingBuilder() 
    .add("userName", "13363114390") 
    .add("password", "200820e3227815ed1756a6b531e7e0d2").build(); 
 
Request build = new Request.Builder().url(url).post(body).build(); 
client.newCall(build).enqueue(new Callback() { 
 
  @Override 
  public void onResponse(Response response) throws IOException { 
    String lenght = response.header("Content-Length"); 
    System.out.println("wisely--lenght:" + lenght); 
 
    LoginResponse loginResponse = new Gson().fromJson(response.body().charStream(), LoginResponse.class); 
    System.out.println("wisely---" + loginResponse.getMessage()); 
  } 
 
  @Override 
  public void onFailure(Request arg0, IOException arg1) { 
    System.out.println("wisely-----fail"); 
  } 
});
Copy after login
String tokeId; 
  boolean result; 
 
  public boolean isResult() { 
    return result; 
  } 
 
  public void setResult(boolean result) { 
    this.result = result; 
  } 
 
  public String getMessage() { 
    return message; 
  } 
 
  public void setMessage(String message) { 
    this.message = message; 
  } 
 
  public String getTokeId() { 
    return tokeId; 
  } 
 
  public void setTokeId(String tokeId) { 
    this.tokeId = tokeId; 
  } 
 
}
Copy after login

The above is a simple login form submission, in which the returned json data is encapsulated into a bean. In addition to obtaining json data, each message header can also be obtained.

2. Upload pictures

This is the function I care about most. Experiments have proved that okHttp has a powerful function of uploading pictures and supports multiple picture uploads.

private MediaType PNG = MediaType.parse("application/octet-stream");
Copy after login
OkHttpClient client = new OkHttpClient(); 
     
RequestBody body = new MultipartBuilder() 
    .type(MultipartBuilder.FORM) 
    .addPart(Headers.of("Content-Disposition","form-data; name=\"files\";filename=\"img1.jpg\""),RequestBody.create(PNG, file1)) 
    .addPart(Headers.of("Content-Disposition","form-data; name=\"files\";filename=\"img2.jpg\""),RequestBody.create(PNG, file2)).build(); 
     
Request request = new Request.Builder() 
  <span style="white-space:pre">  </span>.url(url) 
    .post(body).build(); 
client.newCall(request).enqueue(new Callback() { 
       
  @Override 
  public void onResponse(Response response) throws IOException { 
         
    if(response.isSuccessful()){ 
      UploadPNGResponse uploadPNGResponse = new Gson().fromJson(response.body().charStream(), UploadPNGResponse.class); 
      String msg = uploadPNGResponse.getMsg(); 
           
      List<String> list = uploadPNGResponse.getList(); 
      for (String string : list) { 
        System.out.println("wisely---path:"+string); 
      } 
           
    } 
  } 
       
  @Override 
  public void onFailure(Request arg0, IOException arg1) { 
    System.out.println("wisely---fail--"+arg1.getCause().getMessage()); 
  } 
});
Copy after login
class UploadPNGResponse{  
String msg; 
  boolean result; 
  List<String> list; 
  public String getMsg() { 
    return msg; 
  } 
  public void setMsg(String msg) { 
    this.msg = msg; 
  } 
  public boolean isResult() { 
    return result; 
  } 
  public void setResult(boolean result) { 
    this.result = result; 
  } 
  public List<String> getList() { 
    return list; 
  } 
  public void setList(List<String> list) { 
    this.list = list; 
  } 
}
Copy after login

The above is the detailed content of Detailed explanation of the usage and examples of OkHttp in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!