一 OkHttp介紹
OkHttp是一個優秀的網絡請求框架,目前主流已經替換httpclient, HttpURLConnection 使用方式;
OkHttp支持連接同一地址的鏈接共享同一個socket,通過連接池來減小響應延遲,自帶GZIP壓縮,請求緩存等優勢;
OkHttp 成為 Android 最常見的網絡請求庫, 但並不妨礙java后端學習他,所以這邊知識追尋者 做了常用總結
github: https://github.com/square/okhttp
官方文檔:https://square.github.io/okhttp/
二 依賴
目前最新版本:4.9.0
maven
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
gradle
compile 'com.squareup.okhttp3:okhttp:3.6.0'
三 GET 請求
請求步驟
- 獲取OkHttpClient對象
- 設置請求request
- 封裝call
- 異步調用,並設置回調函數
/**
* @Author lsc
* <p>get 請求 </p>
* @Param [url]
* @Return
*/
public void get(String url){
// 1 獲取OkHttpClient對象
OkHttpClient client = new OkHttpClient();
// 2設置請求
Request request = new Request.Builder()
.get()
.url(url)
.build();
// 3封裝call
Call call = client.newCall(request);
// 4異步調用,並設置回調函數
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// ...
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response!=null && response.isSuccessful()){
// ...
// response.body().string();
}
}
});
//同步調用,返回Response,會拋出IO異常
//Response response = call.execute();
}
四 POST 請求
4.1 form 表單形式
- 獲取OkHttpClient對象
- 構建參數body
- 構建 request
- 將Request封裝為Call
- 異步調用
/**
* @Author lsc
* <p> post 請求, form 參數</p>
* @Param [url]
* @Return
*/
public void postFormData(String url){
// 1 獲取OkHttpClient對象
OkHttpClient client = new OkHttpClient();
// 2 構建參數
FormBody formBody = new FormBody.Builder()
.add("username", "admin")
.add("password", "admin")
.build();
// 3 構建 request
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
// 4 將Request封裝為Call
Call call = client.newCall(request);
// 5 異步調用
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// ...
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response!=null && response.isSuccessful()){
// ...
}
}
});
}
4.2 json參數形式
- 獲取OkHttpClient對象
- 構建參數
- 構建 request
- 將Request封裝為Call
- 異步調用
/**
* @Author lsc
* <p>post 請求 ,json參數 </p>
* @Param [url, json]
* @Return
*/
public void postForJson(String url, String json){
// 1 獲取OkHttpClient對象
OkHttpClient client = new OkHttpClient();
// 2 構建參數
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
// 3 構建 request
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
// 4 將Request封裝為Call
Call call = client.newCall(request);
// 5 異步調用
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// ...
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response!=null && response.isSuccessful()){
// ...
}
}
});
}
如果是json字符串,替換請求媒體類型即可
// 2 構建參數
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:admin;password:admin}");
// 3 構建 request
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
4.3 文件下載
- 獲取OkHttpClient對象
- 構建 request
- 異步調用
- 文件下載
/**
* @Author lsc
* <p> 文件下載 </p>
* @Param url 下載地址url
* @Param target 下載目錄
* @Param target 文件名
* @Return
*/
private void download(String url, String target, String fileName){
// 1 獲取OkHttpClient對象
OkHttpClient client = new OkHttpClient();
// 2構建 request
Request request = new Request.Builder()
.url(url)
.build();
// 3 異步調用
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
// 4 文件下載
downlodefile(response, target,fileName);
}
}
});
}
private void downlodefile(Response response, String url, String fileName) {
InputStream inputStream = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream outputStream = null;
try {
inputStream = response.body().byteStream();
//文件大小
long total = response.body().contentLength();
File file = new File(url, fileName);
outputStream = new FileOutputStream(file);
long sum = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.4 文件上傳
- 獲取OkHttpClient對象
- 封裝參數以 form形式, 媒體格式為二進制流
- 封裝 request
- 異步回調
/**
* @Author lsc
* <p> 文件上傳 </p>
* @Param [url]
* @Return
*/
public void upload(String url){
File file = new File("C:/mydata/generator/test.txt");
if (!file.exists()){
System.out.println("文件不存在");
}else{
// 獲取OkHttpClient對象
OkHttpClient client = new OkHttpClient();
// 2封裝參數以 form形式
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", "admin")
.addFormDataPart("password", "admin")
.addFormDataPart("file", "555.txt", RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
// 3 封裝 request
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
// 4 異步回調
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
}
公眾號知識追尋者,歡迎關注,獲取原創PDF,面試題集;