okHttp 拦截器
可以拦截到我们请求、返回的信息,之后再放入OkHttpClient.Builder()对象中
第一种 httploggingInterceptor
第二种 Intercept
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request build = chain.request().newBuilder().header("token", "123456").build();
return chain.proceed(build);
}
};
mvc 三层关系
首先是定义一个OKHttpUtils 工具类在其中写上需要调用的方法,(上传下载,get/post),然后定义一个接口MyModel,接口中写方法的参数与工具类的方法参数一致,之后再创建一个类去实现MyModel,重写接口中的方法,之后直接new这个类直接调用方法即可
代码
OkHttpUtils
package com.example.paa.HttpUtils;
import android.os.Environment;
import android.os.Handler;
import android.widget.Toast;
import com.example.paa.MyListener.OkListener;
import com.example.paa.Share;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
public class OkHttpUtils {
private static OkHttpUtils okHttpUtils = null;
private OkHttpClient client;
private Handler handler = new Handler();
private OkHttpUtils(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request build = chain.request().newBuilder().header("token", "123456").build();
return chain.proceed(build);
}
};
client = new OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.connectTimeout(20,TimeUnit.SECONDS)
.addInterceptor(interceptor)
.addInterceptor(httpLoggingInterceptor)
.build();
}
public static OkHttpUtils getInstance(){
if (okHttpUtils == null) {
synchronized (Object.class){
if (okHttpUtils == null) {
okHttpUtils = new OkHttpUtils();
}
}
}
return okHttpUtils;
}
public void doPost(String url, Map<String,String> map, final OkListener listener){
FormBody.Builder builder = new FormBody.Builder();
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> stringEntry : entries) {
builder.add(stringEntry.getKey(),stringEntry.getValue());
}
Request request = new Request.Builder()
.header("Connection-Type","application/json")
.header("Connection","keep-alive")
.url(url)
.post(builder.build())
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
listener.getError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
final String string = body.string();
handler.post(new Runnable() {
@Override
public void run() {
listener.getMessage(string);
}
});
}
});
}
public void doGet(String url, final OkListener listener){
Request request = new Request.Builder()
.url(url)
.get()
.header("Connection", "keep-alive")
.header("Connection-Type", "application/json")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
listener.getMessage(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
final String string = body.string();
handler.post(new Runnable() {
@Override
public void run() {
listener.getMessage(string);
}
});
}
});
}
public void downLoad(String url, final File file, final OkListener listener){
Request request = new Request.Builder()
.url(url)
.get()
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
listener.getError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
InputStream inputStream = body.byteStream();
byte[] b = new byte[1024];
int len = 0;
// File directory = Environment.getExternalStorageDirectory();
FileOutputStream fos = new FileOutputStream(file);
while((len = inputStream.read(b)) != -1){
fos.write(b, 0, len);
}
inputStream.close();
fos.close();
handler.post(new Runnable() {
@Override
public void run() {
listener.getMessage("下载成功!");
}
});
}
});
}
public void upLoad(String url, String name, String type, File path, final OkListener listener){
RequestBody requestBody = RequestBody.create(MediaType.parse(type), path);
MultipartBody.Builder addFormDataPart = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", name, requestBody);
Request request = new Request.Builder()
.url(url)
.post(addFormDataPart.build())
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
listener.getError(e.getMessage());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
final String string = body.string();
handler.post(new Runnable() {
@Override
public void run() {
listener.getMessage(string);
}
});
}
});
}
}
MyModel 接口
package com.example.paa.Model;
import com.example.paa.MyListener.OkListener;
import java.io.File;
import java.util.Map;
public interface MyModel {
void Post(String url, Map<String,String> map, OkListener listener);
void Get(String url,OkListener listener);
void downLoad(String url, File file, OkListener listener);
void upLoad(String url,File path,String name,String tyep,OkListener listener);
}
MyModelmpl 实现类
package com.example.paa.Model;
import com.example.paa.HttpUtils.OkHttpUtils;
import com.example.paa.MyListener.OkListener;
import java.io.File;
import java.util.Map;
public class MyModelImpl implements MyModel{
private OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
@Override
public void Post(String url, Map<String, String> map, OkListener listener) {
okHttpUtils.doPost(url,map,listener);
}
@Override
public void Get(String url, OkListener listener) {
okHttpUtils.doGet(url,listener);
}
@Override
public void downLoad(String url, File file, OkListener listener) {
okHttpUtils.downLoad(url,file,listener);
}
@Override
public void upLoad(String url, File path, String name, String type, OkListener listener) {
okHttpUtils.upLoad(url,path,name,type,listener);
}
}
接下来就是Activity中的代码了
登录Activity
package com.example.paa;
import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.paa.HttpUtils.OkHttpUtils;
import com.example.paa.JavaBean.KeyBean;
import com.example.paa.JavaBean.RegisterBean;
import com.example.paa.Model.MyModelImpl;
import com.example.paa.MyListener.OkListener;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private OkHttpUtils instance;
private MyModelImpl myModel;
private String path = "https://www.apiopen.top/createUserKey";
private String login_url = "https://www.apiopen.top/login";
private String appKey = "";
private EditText editUser;
private EditText editPwd;
private Button buttonLogins;
private Button butToRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
String[] str = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(str,100);
}
instance = OkHttpUtils.getInstance();
myModel = new MyModelImpl();
initView();
}
private void initView() {
editUser = findViewById(R.id.edit_user);
editPwd = findViewById(R.id.edit_pwd);
buttonLogins = findViewById(R.id.button_logins);
butToRegister = findViewById(R.id.but_To_register);
getAppKey();
}
private void getAppKey() {
//?appId=com.aew.wlsj&passwd=123456
Map<String, String> map = new HashMap<>();
map.put("appId", "com.pan.w");
map.put("passwd", "123321");
myModel.Post(path, map, new OkListener() {
@Override
public void getError(String error) {
}
@Override
public void getMessage(String msg) {
KeyBean keyBean = new Gson().fromJson(msg, KeyBean.class);
appKey = keyBean.getData().getAppkey();
Toast.makeText(MainActivity.this, "" + appKey, Toast.LENGTH_SHORT).show();
}
});
buttonLogins.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String pwd = editPwd.getText().toString().trim();
String user = editUser.getText().toString().trim();
//?key=00d91e8e0cca2b76f515926a36db68f5&phone=13594347817&passwd=123456
Map<String,String> map = new HashMap<>();
map.put("key",appKey);
map.put("phone",user);
map.put("passwd",pwd);
myModel.Post(login_url, map, new OkListener() {
@Override
public void getError(String error) {
Toast.makeText(MainActivity.this, "未知错误:"+error, Toast.LENGTH_SHORT).show();
}
@Override
public void getMessage(String msg) {
RegisterBean registerBean = new Gson().fromJson(msg, RegisterBean.class);
Toast.makeText(MainActivity.this, ""+registerBean, Toast.LENGTH_SHORT).show();
if(registerBean.getCode() == 200){
Toast.makeText(MainActivity.this, "登陆成功!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, ShowActivity.class);
startActivity(intent);
finish();
}else{
Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
}
}
});
}
});
butToRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(appKey.equals("")){
Toast.makeText(MainActivity.this, "系统繁忙,请稍后"+"<"+appKey+">", Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
intent.putExtra("appKey",appKey);
startActivity(intent);
}
});
}
}
注册页面
package com.example.paa;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.paa.JavaBean.RegisterBean;
import com.example.paa.Model.MyModelImpl;
import com.example.paa.MyListener.OkListener;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {
private EditText editReUser;
private EditText editRePwd;
private Button butReRegister;
private String appKey = "";
//资源
private String post_url = "https://www.apiopen.top/createUser";
//mvc
private MyModelImpl myModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Intent intent = getIntent();
appKey = intent.getStringExtra("appKey");
Toast.makeText(this, ""+appKey, Toast.LENGTH_SHORT).show();
myModel = new MyModelImpl();
initView();
}
private void initView() {
editReUser = findViewById(R.id.edit_re_user);
editRePwd = findViewById(R.id.edit_re_pwd);
butReRegister = findViewById(R.id.but_re_register);
butReRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String user = editReUser.getText().toString().trim();
String pwd = editRePwd.getText().toString().trim();
//?key=00d91e8e0cca2b76f515926a36db68f5&phone=13594347817&passwd=123654
Map<String,String> map = new HashMap<>();
map.put("key",appKey);
map.put("phone",user);
map.put("passwd",pwd);
Log.i("---", "onClick: "+map.toString());
myModel.Post(post_url, map, new OkListener() {
@Override
public void getError(String error) {
Toast.makeText(RegisterActivity.this, "未知原因"+error, Toast.LENGTH_SHORT).show();
}
@Override
public void getMessage(String msg) {
RegisterBean registerBean = new Gson().fromJson(msg, RegisterBean.class);
Log.i("---", "getMessage: "+registerBean.toString());
if(registerBean.getCode() == 200){
Toast.makeText(RegisterActivity.this, "注册成功!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
finish();
}else{
Toast.makeText(RegisterActivity.this, "此用户已被注册!", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
展示抖音数据页面及上传下载
package com.example.paa;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.paa.JavaBean.ShowBean;
import com.example.paa.Model.MyModelImpl;
import com.example.paa.MyAdapter.ShowAdapter;
import com.example.paa.MyListener.OkListener;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ShowActivity extends AppCompatActivity {
private static final String TAG = "---";
private ListView listShow;
private MyModelImpl myModel;
//上传服务器的路径
private String upLoad_url = "http://192.168.43.79/hfs/";
private int start = 0;
private int end = 0;
private String data_url = "https://www.apiopen.top/satinApi";
private List<ShowBean.DataBean> totalList = new ArrayList<>();
private List<String> nameList = new ArrayList<>();
//适配器
private ShowAdapter adapter;
//搞事情
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
String[] str = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(str,100);
}
myModel = new MyModelImpl();
initView();
}
private void initView() {
listShow = findViewById(R.id.list_show);
getData();
intoListView();
}
private void intoListView() {
listShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Share.index = position;
downLoad(position);
}
});
listShow.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(totalList.get(position).getVideouri().equals("") ){
Toast.makeText(ShowActivity.this, "此视频可能不存在或者已被删除!", Toast.LENGTH_SHORT).show();
return false;
}
upLoad(position);
return true;
}
});
}
private void upLoad(final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示信息");
builder.setMessage("确定要上传本地的该视频吗?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File directory = Environment.getExternalStorageDirectory();
File file = new File(directory, nameList.get(position));
myModel.upLoad(upLoad_url, file, nameList.get(position), "media/mp4", new OkListener() {
@Override
public void getError(String error) {
Toast.makeText(ShowActivity.this, ""+error, Toast.LENGTH_SHORT).show();
}
@Override
public void getMessage(String msg) {
Toast.makeText(ShowActivity.this, ""+msg, Toast.LENGTH_SHORT).show();
}
});
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
//下载方法
private void downLoad(final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示信息");
builder.setMessage("确定要下载内容所含视频吗?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(totalList.get(position).getVideouri().equals("") ){
Toast.makeText(ShowActivity.this, "此视频可能不存在或者已被删除!", Toast.LENGTH_SHORT).show();
return;
}
File directory = Environment.getExternalStorageDirectory();
File file = new File(directory, nameList.get(position));
if(file.exists()){
Toast.makeText(ShowActivity.this, "下载过了", Toast.LENGTH_SHORT).show();
return;
}
myModel.downLoad(totalList.get(position).getVideouri(), file, new OkListener() {
@Override
public void getError(String error) {
Toast.makeText(ShowActivity.this, ""+error, Toast.LENGTH_SHORT).show();
}
@Override
public void getMessage(String msg) {
Toast.makeText(ShowActivity.this, ""+msg, Toast.LENGTH_SHORT).show();
}
});
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void getData() {
//?type=1&page=2
final Map<String,String> map = new HashMap<>();
map.put("type","1");
map.put("page","2");
myModel.Post(data_url, map, new OkListener() {
@Override
public void getError(String error) {
Toast.makeText(ShowActivity.this, "未知错误"+error, Toast.LENGTH_SHORT).show();
}
@Override
public void getMessage(String msg) {
ShowBean showBean = new Gson().fromJson(msg, ShowBean.class);
totalList = showBean.getData();
for (int i = 0; i < totalList.size(); i++) {
nameList.add("FunnyVideo"+i+".mp4");
}
Log.i("---", "intoListView: "+totalList.toString());
adapter = new ShowAdapter(totalList,ShowActivity.this);
listShow.setAdapter(adapter);
}
});
}
}