java 中OkHttp的使用方法及實例
java 中OkHttp的使用方法及實例
概述
準備研究Retrofit,而它是依賴OkHttp的,所以先使用一下OkHttp,不深究源碼,只探究使用方法。以后有機會再翻查源碼。
在進行之前,首先需要2個jar包,其中一個是okHttp的jar包,github上可以下載,另一個是它的依賴包,這個很關鍵,沒有它,項目就無法運行。
OkHttp請求的2種方式
不難猜測,涉及到網絡請求,那么無非2種方式,一種是使用回調,另一種則是開啟子線程執(zhí)行。
第一種:開啟子線程執(zhí)行
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();
}
第二種:使用回調,我個人最喜歡使用這種。(PS:覺得自己真是too young too simple!!本來以為回調的方法是在主線程,結果發(fā)現,竟然是子線程,子線程....)
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");
}
});
OkHttp之get請求
1、獲取圖片
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());
}
});
只寫了關鍵代碼,并未寫handler的相關代碼。
獲取網絡圖片有2種方式,1是獲取byte數組,2是獲取輸入流。注意,onResponse在子線程中...
OkHttp之post請求
比起get請求,post請求的分類略多。
1、首先是最常用的表單提交。
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");
}
});
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;
}
}
上面的是一個簡單的登錄表單的提交,其中將返回的json數據封裝到了一個bean中。除了能夠獲取json數據外,還能獲取到各個消息頭。
2、上傳圖片
這是我最關心的一個功能,實驗證明,okHttp上傳圖片的功能確實強大,支持多圖片上傳。
private MediaType PNG = MediaType.parse("application/octet-stream");
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());
}
});
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;
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
java Swing實現選項卡功能(JTabbedPane)實例代碼
這篇文章主要介紹了java Swing實現選項卡功能(JTabbedPane)實例代碼的相關資料,學習java 基礎的朋友可以參考下這個簡單示例,需要的朋友可以參考下2016-11-11
springboot+vue實現Token自動續(xù)期(雙Token方案)
雙Token方案通過訪問令牌和刷新令牌提高用戶登錄安全性和體驗,訪問令牌有效期短,包含用戶信息,用于請求校驗,本文就來介紹一下springboot+vue實現Token自動續(xù)期(雙Token方案),感興趣的可以了解一下2024-10-10
如何在java 8 stream表達式實現if/else邏輯
這篇文章主要介紹了如何在java 8 stream表達式實現if/else邏輯,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04
Maven介紹與配置+IDEA集成Maven+使用Maven命令小結
Maven是Apache軟件基金會的一個開源項目,是一個優(yōu)秀的項目構建管理工具,它用來幫助開發(fā)者管理項目中的 jar,以及 jar 之間的依賴關系、完成項目的編譯、測試、打包和發(fā)布等工作,本文給大家介紹Maven介紹與配置+IDEA集成Maven+使用Maven命令,感興趣的朋友一起看看吧2024-01-01

