代码复用强,少写多余的代码+节省系统的资源(只有一个Client对象)
单例的gongju类:构造私有化+自行实例化+提供公开的方法
导依赖:
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
package com.example.day3_okhttp;
import android.util.Log;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* 1.单例模式工具类,保证只有一个OkhttpClient
* 构造私有化---自行实例化---公开方法
*
* */
public class OkhttpUtils {
private static OkHttpClient client;//只会有一个
private OkhttpUtils(){}
private static OkhttpUtils okhttpUtils=new OkhttpUtils();
public static OkhttpUtils getInstance(){//只会走一次
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(5, TimeUnit.SECONDS);
builder.callTimeout(5,TimeUnit.SECONDS);
//添加log拦截器
builder.addInterceptor(httpLoggingInterceptor);
//添加Token拦截器:为每个请求添加请求头
builder.addInterceptor(tokenInterceptor);
client=builder.build();
return okhttpUtils;
}
//log打印拦截器
static HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("ytx", "log: "+message);
}
});
//token拦截器
static Interceptor tokenInterceptor=new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();//获得request杜希昂
// Request.Builder builder = request.newBuilder();
// builder.header("token","1704");//设置请求头
// Request request1 = builder.build();//创建新的request
Request request = chain.request().newBuilder().header("token", "1704").build();
return chain.proceed(request);
}
};
/***
*
* @param url 网址
* @param myCallback 回调的接口
*/
public void doget(String url, final MyCallback myCallback){
Request request = new Request.Builder()
.get()
.url(url)
.header("token","123")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myCallback.onError(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
myCallback.onSuccess(response);
}
});
}
/***
*
* @param url 网址
* @param map 请求体 键值对形式存在的
*/
public void dopost(String url, final HashMap<String,String> map, final MyCallback myCallback){
//请求体
FormBody.Builder builder = new FormBody.Builder();
//遍历map集合
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry:entries) {
String key = entry.getKey();
String value = entry.getValue();
builder.add(key,value);
}
FormBody formBody = builder.build();
//请求
Request request = new Request.Builder()
.post(formBody)
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myCallback.onError(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
myCallback.onSuccess(response);
}
});
}
public void download(String url,String path,MyCallback myCallback){
}
public void upload(){
}
}
package com.example.day3_okhttp;
import android.os.Handler;
import android.os.Message;
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.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* 一。简单介绍:
* okhttp是一个第三方类库,用于android中请求网络。
* 这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection
* 二。如何使用?get请求和post请求
* 2.HttpClient:客户端对象
* 3.Request对象
* 4.Call :连接
* 5.Response响应
* 三。技能掌握要点:
* 1.get请求,请求json串
* 2.post请求,登陆注册功能 FormBody
* 3.下载文件到SD卡中 get请求
* 4.上传文件 post请求 MultipartBody
*
* 四。okhttp的封装:
*
* */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button bt_sd,bt_json,bt_login,bt_zhuce,bt_upload;
public static final int GET_JSON_OK=102;
public static final int GET_SD_OK=202;
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==GET_JSON_OK){
Toast.makeText(MainActivity.this, ""+msg.obj, Toast.LENGTH_SHORT).show();
}else if(msg.what==GET_SD_OK){
Toast.makeText(MainActivity.this, ""+msg.obj, Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_sd=findViewById(R.id.bt_sd);
bt_sd.setOnClickListener(this);
bt_json=findViewById(R.id.bt_json);
bt_json.setOnClickListener(this);
bt_login=findViewById(R.id.bt_login);
bt_login.setOnClickListener(this);
bt_zhuce=findViewById(R.id.bt_zhuce);
bt_zhuce.setOnClickListener(this);
bt_upload=findViewById(R.id.bt_upload);
bt_upload.setOnClickListener(this);
getjson();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bt_json:
getjson();
break;
case R.id.bt_sd:
sd();
break;
case R.id.bt_zhuce:
zhuce();
break;
case R.id.bt_upload:
try {
upload();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
private void upload() throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
//上传文件的请求体
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);//form提交
RequestBody body = RequestBody.create(MediaType.parse("media/mp4"), new File("/sdcard/a.mp4"));
builder.addFormDataPart("file","1604.mp4",body);
MultipartBody multipartBody = builder.build();
final Request request = new Request.Builder()
.url("http://172.21.79.88/hfs")
.post(multipartBody)//post提交必须要设置请求体
.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 {
}
});
}
//post请求完成注册
private void zhuce() {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
//请求体:phone=13594347817&passwd=123654
FormBody formBody = new FormBody.Builder()
.add("phone", "13594343356")
.add("passwd", "123654")
.build();
final Request request = new Request.Builder()
.url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&")
.post(formBody)//post提交必须要设置请求体
.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 string = response.body().string();
Message obtain = Message.obtain();
obtain.what=GET_JSON_OK;
obtain.obj=string;
handler.sendMessage(obtain);
}
});
}
//下载文件到SD卡中
private void sd() {
//TODO 1:client
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.callTimeout(5, TimeUnit.SECONDS)
.build();
//TODO 2:request
Request request = new Request.Builder()
.get()
.url("http://169.254.113.244/hfs/a.jpg")
.build();
//TODO 3:call
Call call = client.newCall(request);
//TODO 4:response
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {//失败
}
@Override
public void onResponse(Call call, Response response) throws IOException {//成功
ResponseBody body = response.body();
// byte[] bytes = body.bytes();
long l = body.contentLength();
InputStream inputStream = body.byteStream();
int read = inputStream.read();
FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/ok.jpg");
// fileOutputStream.write(bytes);
Message obtain = Message.obtain();
obtain.what=GET_SD_OK;
obtain.obj="下载成功";
handler.sendMessage(obtain);
}
});
}
//网络请求json串
public void getjson(){
//TODO 1:client
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.callTimeout(5, TimeUnit.SECONDS);//连接超时
builder.readTimeout(5,TimeUnit.SECONDS);//读取超时
OkHttpClient client = builder.build();
//TODO 2:request对象
Request.Builder builder1 = new Request.Builder();
builder1.url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&");//设置网址
builder1.get();//设置请求方法
FormBody.Builder builder2 = new FormBody.Builder();
builder2.add("page","1");
builder1.post(builder2.build());
Request request = builder1.build();
//TODO 3:发起连接call
Call call = client.newCall(request);
//TODO 4:通过call得到response
call.enqueue(new Callback() {
//请求失败
@Override
public void onFailure(Call call, IOException e) {
}
//请求成功
@Override
public void onResponse(Call call, Response response) throws IOException {
//获得响应体:json串
ResponseBody body = response.body();
//通过body直接转成字符串
String json = body.string();
// Toast.makeText(MainActivity.this, ""+json, Toast.LENGTH_SHORT).show();
Message obtain = Message.obtain();
obtain.what=GET_JSON_OK;
obtain.obj=json;
handler.sendMessage(obtain);
}
});
}
}