前言
由于前段时间参加学校比赛,都没有时间来更新博客,这里给大家带来一篇非常实用的文章
本文类容
安卓如何通过okhttp2.0上传数据、文件,而我们的后端采用的是spring boot2.0来接收我们的上传的数据
前期准备
1、导入箭头所指向的这两个包,如果没有则点击这里进行下载https://download.csdn.net/download/weixin_43055096/11148006
2、由于我们要上传文件图片,所以我们必须要加入权限,而安卓6.0之后对权限要求很严格,不仅要在xml里面配置,还要写到我们的程序中。(按照小编的写法写好我们的xml,后面的还会说道我们手动权限的配置)
之后我们就可以开始我们的数据上传了。
这里小编给大家写了一个工具类,
package activity.sleephousekeeper.Utils;
import android.util.Log;
import java.io.File;
import java.util.Map;
import java.util.Set;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class OkhttpUtil {
private static OkhttpUtil instance;
private OkhttpUtil(){
}
public static OkhttpUtil getInstance(){
if(instance == null){
instance = new OkhttpUtil();
}
return instance;
}
/**
* 通过get 提交
* @param url
* @return
*/
public Call get(String url){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
return call;
}
/**
* 通过post方式提交表单
* @param url 提交地址
* @param map 表单数据
* @return Call
*/
public Call post(String url, Map<String,Object> map){
OkHttpClient client = new OkHttpClient();
FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
Set<String> keys = map.keySet();
for(String k:keys){
formBody.add(k,map.get(k).toString());
}
Request request = new Request.Builder()
.url(url)
.post(formBody.build())
.build();
return client.newCall(request);
}
/**
* 通过post提交json数据
* @param url 提交地址
* @param json 提交的实例
* @return call
*/
public Call post(String url,String json){
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, json);
Request request = new Request.Builder()
.url(url)//请求的url
.post(requestBody)
.build();
return client.newCall(request);
}
/**
* okhttp对文件的操作
* @param filepath 文件路径
* @param url 文件地址
* @param filename //文件名称
* @return
*/
public Call file_submit(String filepath,String url,String filename){
OkHttpClient client = new OkHttpClient();
File file = new File(filepath);
Log.i("text",filepath);
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
//请求体
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(Headers.of(
"Content-Disposition",
"form-data; name=\"filename\""),
RequestBody.create(null, "lzr"))//这里是携带上传的其他数据
.addPart(Headers.of(
"Content-Disposition",
"form-data; name=\"mFile\"; filename=\"" + filename + "\""), fileBody)
.build();
//请求的地址
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
return client.newCall(request);
}
}
手动申请权限
在我们的MainActivity中加入这样一行代码,并且在主页面运行的时候启动这个方法(这里开启的是对文件读写的操作)
// An highlighted block
private void myRequetPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
Toast.makeText(this, "您已经申请了权限!", Toast.LENGTH_SHORT).show();
}
}
安卓上传数据代码
public void LoginClick(View v) {
progressDialog = ProgressDialog.show(LoginActivity.this, "登录中......", "");
switch (v.getId()) {
case R.id.text_registe:
showToast(LoginActivity.this, "前往注册界面");
startActivity(new Intent(LoginActivity.this, RegistActivity.class));
break;
case R.id.btn_login:
new Thread(new Runnable() {
@Override
public void run() {
final String username = musername.getText().toString();
String password = mpassword.getText().toString();
//这里就是我们数据上传的地址
String url = "http://192.168.43.104:8080/userLogin/submit";
Map<String, Object> map = new HashMap<>();
map.put("username", username);
map.put("password", password);
Call call = OkhttpUtil.getInstance().post(url, map);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Looper.prepare();
Toast toast = Toast.makeText(LoginActivity.this, "登录失败......", Toast.LENGTH_SHORT);
progressDialog.dismiss();
toast.show();
Looper.loop();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
Log.i("success........", "成功" + json);
}
});
}
}).start();
break;
default:
break;
}
}
注意任何耗时操作一定不能直接写在主线程内,一定要开启另外一个分线程进行
后端接收安卓上传数据代码(这里采用的是spring boot作为后台)
@RequestMapping(value = "/userLogin/submit",method = RequestMethod.POST)
public String userLogin(HttpServletRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username);
HttpSession session = request.getSession();
User u = usi.findUserByUsernameAndPassowrd(username,password);
Result r = new Result();
if (u==null){
r.setCode(10001);
r.setMessage("用户名不存在");
}else {
r.setCode(200);
r.setMessage("登录成功");
r.setData(u);
session.setAttribute("id",username);
System.out.println("已经把username放入session中");
}
System.out.println((String) session.getAttribute("id"));
return GsonUtil.ObjectToString(r);
}
那么我们的文件、图片上传呢
public void text(View view){
switch (view.getId()){
case R.id.file_submit:
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
//这里小编是自定义了一个textPath
String textPath="/sdcard/1243/12.txt";
File file = new File(textPath);
filename = textPath.substring(textPath.lastIndexOf("/") + 1);
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(Headers.of(
"Content-Disposition",
"form-data; name=\"getUpTime\""),
RequestBody.create(null, "2019-3-29"))
.addPart(Headers.of(
"Content-Disposition",
"form-data; name=\"originalData\"; filename=\"" + filename + "\""), fileBody)
.build();
String url = "http://192.168.43.104:8080/file";
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("text", "failure upload!");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("text", "success upload!");
String json = response.body().string();
Log.i("success........","成功"+json);
}
});
}
}).start();
break;
}
}
Spring boot 文件接收后台
//文件上传
@PostMapping(value = "/file")
public String fileUpload(@RequestParam(value = "originalData") MultipartFile file, Model model, HttpServletRequest request) {
if (file.isEmpty()) {
System.out.println("文件为空空");
}
System.out.println("文件开始上传");
String fileName = file.getOriginalFilename(); // 文件名
System.out.println(fileName);
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
//上传到服务器之中了
// String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
String filePath = "D://aaa/";
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs(); }
try { file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
String filename = "/temp-rainy/" + fileName;
model.addAttribute("filename", filename);
return "file";
}
当我们点击文件上传时
我们后台也就开始接收到我么上传的文件或者是图片了
我们的文件也被相应的保存在了D盘