//封装的工具类
package
com.example.okhttp_fenzhuang.util;
import
android.os.Handler;
import
java.io.IOException;
import
java.util.Map;
import
java.util.Set;
import
java.util.concurrent.TimeUnit;
import
okhttp3.Call;
import
okhttp3.Callback;
import
okhttp3.FormBody;
import
okhttp3.OkHttpClient;
import
okhttp3.Request;
import
okhttp3.RequestBody;
import
okhttp3.Response;
public class
RequestDataUtil {
private static
OkHttpClient
client
;
private static
Handler
handler
;
//构造方法
private
RequestDataUtil() {
client
=
new
OkHttpClient.Builder()
.connectTimeout(
10
, TimeUnit.
SECONDS
)
.writeTimeout(
10
, TimeUnit.
SECONDS
)
.readTimeout(
10
, TimeUnit.
SECONDS
)
.build();
handler
=
new
Handler();
}
private static final
RequestDataUtil
dataUtil
=
new
RequestDataUtil();
public static
RequestDataUtil getInstance(){
return
dataUtil
;
}
//定义接口
public interface
IcallBack{
void
onResponse(String jsonData);
//请求数据是Json数据时使用
}
public interface
IcallBack2{
void
onResponse(
byte
[] bytes);
//请求数据是时使用
}
public interface
IcallBack3{
void
onResponse(String jsonData);
//请求数据是Json数据时使用
}
//将编程的代码运行到主线程中
//处理请求网络成功的方法,返回的结果是Json字符串
public static void
requestJsonDataOk(
final
String jsonData,
final
IcallBack icallBack){
handler
.post(
new
Runnable() {
@Override
public void
run() {
if
(
icallBack
!=
null
){
icallBack
.onResponse(
jsonData
);
}
}
});
}
public static void
requestJsonDataOk3(
final
String jsonData,
final
IcallBack3 icallBack){
handler
.post(
new
Runnable() {
@Override
public void
run() {
if
(
icallBack
!=
null
){
icallBack
.onResponse(
jsonData
);
}
}
});
}
//处理请求网络成功的方法,返回的结果是byte数组
public static void
requestByteOk(
final byte
[] bytes,
final
IcallBack2 icallBack){
handler
.post(
new
Runnable() {
@Override
public void
run() {
if
(
icallBack
!=
null
){
icallBack
.onResponse(
bytes
);
}
}
});
}
//-------------------------------------------------------------------------------------------------------
//提供外部调用的方法
/**
* 请求指定的URL返回的结果是Json字符串
*/
public static void
setRequestJsonData(String myUrl,
final
IcallBack icallBack){
Request request =
new
Request.Builder().url(myUrl).build();
Call call =
client
.newCall(request);
call.enqueue(
new
Callback() {
@Override
public void
onFailure(Call call, IOException e) {
//请求失败
}
@Override
public void
onResponse(Call call, Response response)
throws
IOException {
//请求成功
String jsonData = response.body().string();
requestJsonDataOk
(jsonData,
icallBack
);
//调用请求成功时执行的方法
}
});
}
/**
* 请求指定的URL返回的结果是byte数组
*/
public static void
setRrequestByte(String myUrl,
final
IcallBack2 icallBack){
Request request =
new
Request.Builder().url(myUrl).build();
Call call =
client
.newCall(request);
call.enqueue(
new
Callback() {
@Override
public void
onFailure(Call call, IOException e) {}
@Override
public void
onResponse(Call call, Response response)
throws
IOException {
byte
[] bytes = response.body().bytes();
requestByteOk
(bytes,
icallBack
);
//调用请求成功时执行的方法
}
});
}
/**
* 请求指定的URL返回的结果是Json字符串 这个是提交表单
*/
public static void
setRequestJsonData3(String myUrl, Map map,
final
IcallBack3 icallBack3){
//创建表单
FormBody.Builder builder =
new
FormBody.Builder();
//得到map集合当中的数据
for
(Map.Entry entry : map.entrySet() ) {
builder.add(entry.getKey(),entry.getValue());
}
RequestBody requestBody = builder.build();
Request request =
new
Request.Builder().post(requestBody).url(myUrl).build();
Call call =
client
.newCall(request);
call.enqueue(
new
Callback() {
@Override
public void
onFailure(Call call, IOException e) {}
@Override
public void
onResponse(Call call, Response response)
throws
IOException {
//请求成功
String jsonData = response.body().string();
requestJsonDataOk3
(jsonData,
icallBack3
);
//调用请求成功时执行的方法
}
});
}
}
//网络请求的工具类
------------------------------------------------------------------
package
com.example.okhttp_fenzhuang;
import
android.graphics.Bitmap;
import
android.graphics.BitmapFactory;
import
android.support.v7.app.AppCompatActivity;
import
android.os.Bundle;
import
android.util.Log;
import
android.view.View;
import
android.widget.Button;
import
android.widget.ImageView;
import
android.widget.TextView;
import
com.example.okhttp_fenzhuang.util.RequestDataUtil;
import
com.google.gson.Gson;
import
java.util.HashMap;
public class
MainActivity
extends
AppCompatActivity
implements
View.OnClickListener {
private
Button
btn_img
;
private
Button
btn_log
;
private
Button
btn_request
;
private
ImageView
imageView
;
private
TextView
txt_content
;
private
String
myUrlJson
=
"http://api.tianapi.com/world/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"
;
private
String
muUrlImg
=
"http://s13.sinaimg.cn/mw690/003WdrRCty6DP7FOPi48c&690"
;
private
String
muUrlPost
=
"https://www.zhaoapi.cn/user/getUserInfo"
;
@Override
protected void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main
);
initView();
//初始化
}
private void
initView() {
//获取资源id
btn_img
= findViewById(R.id.
btn_img
);
。。。。。。。。。自己写
}
@Override
public void
onClick(View view) {
//得到网络请求的工具类
RequestDataUtil dataUtil = RequestDataUtil.
getInstance
();
switch
(view.getId()){
case
R.id.
btn_img
:
//下载图片
dataUtil.
setRrequestByte
(
muUrlImg
,
new
RequestDataUtil.IcallBack2() {
@Override
public void
onResponse(
byte
[] bytes) {
Bitmap bitmap = BitmapFactory.
decodeByteArray
(bytes,
0
, bytes.
length
);
imageView
.setImageBitmap(bitmap);
}
});
break
;
case
R.id.
btn_log
:
//模拟登陆Post请求
HashMap map =
new
HashMap<>();
map.put(
"uid"
,
"123"
);
map.put(
"id"
,
"7"
);
dataUtil.
setRequestJsonData3
(
muUrlPost
, map,
new
RequestDataUtil.IcallBack3() {
@Override
public void
onResponse(String jsonData) {
Gson gson =
new
Gson();
MyGson myGson = gson.fromJson(jsonData, MyGson.
class
);
String msg = myGson.getMsg();
txt_content
.setText(msg);
}
});
break
;
case
R.id.
btn_request
:
//请求的是json数据
dataUtil.
setRequestJsonData
(
myUrlJson
,
new
RequestDataUtil.IcallBack() {
@Override
public void
onResponse(String jsonData) {
Log.
d
(
"zzzz"
,
"onResponse: "
+jsonData);
}
});
break
;
}
}
}