okhttp
导入依赖
“implementation ‘com.squareup.okhttp3:okhttp:3.12.1’”
okutils get请求 post请求 下载
public class OkHttpUtils {
private static final String TAG = "OkHttpUtils";
private OkHttpClient okHttpClient;
private Handler handler = new Handler();
private OkHttpUtils() {
okHttpClient = new OkHttpClient.Builder()
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.build();
}
private static OkHttpUtils okHttpUtils = new OkHttpUtils();
public static OkHttpUtils getInstance() {
return okHttpUtils;
}
//get请求
/*
第一个参数 网址
第二个参数 接口
*/
public void doget(String url, final OkHttpCallBack okHttpCallBack) {
final Request request = new Request.Builder().get().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
okHttpCallBack.onError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String string = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
okHttpCallBack.onOk(string);
}
});
}
});
}
//post请求
/*
第一个参数 网址
第二个参数 数据
第三个参数 接口
*/
public void dopost(String url, HashMap<String, String> map, final OkHttpCallBack okHttpCallBack) {
FormBody.Builder builder = new FormBody.Builder();
//获取键值对集合
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();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
okHttpCallBack.onError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String string = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
Log.i(TAG, "run: "+string);
okHttpCallBack.onOk(string);
}
});
}
});
}
//下载
/*
第一个参数 网址
第二个参数 路径
第三个参数 接口
*/
public void download(String url, final String path, final OkHttpCallBack okHttpCallBack) {
Request request = new Request.Builder()
.get()
.url(url)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
okHttpCallBack.onError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = new FileOutputStream(path);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
handler.post(new Runnable() {
@Override
public void run() {
okHttpCallBack.onOk("下载成功");
}
});
}
});
}
}
OkhttpCallBack
public interface OkHttpCallBack {
void onError(String message);
void onOk(String message);
}
注册
public class OneFragment extends Fragment {
private EditText registerName;
private EditText registerPassword;
private Button registerId;
private String urlstring = "http://49.233.93.155:8080/register";
private Handler handler = new Handler();
public OneFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inflate = inflater.inflate(R.layout.fragment_one, container, false);
registerName = (EditText) inflate.findViewById(R.id.register_name);
registerPassword = (EditText) inflate.findViewById(R.id.register_password);
registerId = (Button) inflate.findViewById(R.id.register_id);
return inflate;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 获取输入的字符串
HashMap<String, String> map = new HashMap<>();
map.put("username", registerName.getText().toString());
map.put("password", registerPassword.getText().toString());
OkHttpUtils.getInstance().dopost(urlstring, map, new OkHttpCallBack() {
@Override
public void onError(String message) {
Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
}
@Override
public void onOk(String json) {
ResisterBean resisterBean = JSON.parseObject(json, ResisterBean.class);
if (resisterBean.getCode().equals("200")) {
SharedPreferences users = getActivity().getSharedPreferences("users", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = users.edit();
edit.putBoolean("flag", true);
//提交
edit.commit();
MainActivity.viewId.setCurrentItem(1);
Toast.makeText(getContext(), "" + resisterBean.getResult(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "" + resisterBean.getResult() , Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
登陆
public class TwoFragment extends Fragment {
private static final String TAG = "TwoFragment";
private EditText loginName;
private EditText loginPassword;
private Button loginId;
private String urlString = "http://49.233.93.155:8080/login";
private Handler handler = new Handler();
public TwoFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inflate = inflater.inflate(R.layout.fragment_two, container, false);
loginName = (EditText) inflate.findViewById(R.id.login_name);
loginPassword = (EditText) inflate.findViewById(R.id.login_password);
loginId = (Button) inflate.findViewById(R.id.login_id);
return inflate;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
HashMap<String, String> map = new HashMap<>();
map.put("name", loginName.getText().toString());
map.put("password", loginPassword.getText().toString());
OkHttpUtils.getInstance().dopost(urlString, map, new OkHttpCallBack() {
@Override
public void onError(final String message) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onOk(String json) {
Log.i(TAG, "onOk: "+json);
LoginBean loginBean = JSON.parseObject(json, LoginBean.class);
if (loginBean.getCode().equals("200")) {
SharedPreferences users = getActivity().getSharedPreferences("users", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = users.edit();
edit.putString("token", loginBean.getResult().getToken());
edit.commit();
Toast.makeText(getContext(), "" + loginBean.getMessage(), Toast.LENGTH_SHORT).show();
MainActivity.viewId.setCurrentItem(2);
} else {
Toast.makeText(getContext(), "" + loginBean.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
下载
public class ThreeFragment extends Fragment {
private ListView listId;
private List<FoodBean.DataBean> dataBeans = new ArrayList<>();
private Handler handler = new Handler();
private String stringurl = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
private String pic;
private String title;
public ThreeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inflate = inflater.inflate(R.layout.fragment_three, container, false);
listId = (ListView) inflate.findViewById(R.id.list_id);
return inflate;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
OkHttpUtils.getInstance().doget(stringurl, new OkHttpCallBack() {
@Override
public void onError(final String message) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onOk(String json) {
FoodBean foodBean = JSON.parseObject(json, FoodBean.class);
List<FoodBean.DataBean> data = foodBean.getData();
dataBeans.addAll(data);
handler.post(new Runnable() {
@Override
public void run() {
MyAdapter myAdapter = new MyAdapter(getContext(), dataBeans);
listId.setAdapter(myAdapter);
}
});
}
});
listId.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pic = dataBeans.get(position).getPic();
title = dataBeans.get(position).getTitle();
final PopupWindow popupWindow = new PopupWindow(getContext());
View inflate = LayoutInflater.from(getContext()).inflate(R.layout.layout_pop, null);
//三要素
popupWindow.setContentView(inflate);
popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
Button download = inflate.findViewById(R.id.downlod_id);
Button cancel = inflate.findViewById(R.id.cancel_id);
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//设置存储地址
String path = "/sdcard/DCIM/" + title + ".jpg";
File file = new File(path);
//判断路径是否存在
if (file.exists()) {
Toast.makeText(getContext(), "已存在", Toast.LENGTH_SHORT).show();
} else {
OkHttpUtils.getInstance().download(pic, path, new OkHttpCallBack() {
@Override
public void onError(String message) {
Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
}
@Override
public void onOk(String json) {
Toast.makeText(getContext(), "" + json, Toast.LENGTH_SHORT).show();
}
});
}
popupWindow.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
popupWindow.showAtLocation(inflate, Gravity.BOTTOM, 0, 0);
}
});
}
}