直接上代码
public class MainActivity extends AppCompatActivity {
private TextView tv;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPers();
initView();
}
private void initView() {
tv = findViewById(R.id.tv);
btn = findViewById(R.id.btn);
//点击按钮后开始上传
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
upload();
}
});
}
//动态授权
private void initPers() {
String[] pers = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
ActivityCompat.requestPermissions(this, pers, 1);
}
public void upload() {
File file1 = new File(Environment.getExternalStorageDirectory() + "/com.mypro/" + "aaa.mp3"); //本地音频文件
if (file1 == null) {
//文件不存在
return;
}
final String url = "https://api.steponeai.com/api/v1/upload";
// File file = new File(Environment.getExternalStorageDirectory() + "/1560237648804.amr"); //本地音频文件
//if (bool) {
//如果文件存在
OkHttpClient okHttpClient = new OkHttpClient.Builder().build(); //创建Okhttpclient对象
//创建requestBody对象 封装文件格式
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file1);
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("company_id", company_id, requestBody)//第一个参数为后台定好的字段名称
.addFormDataPart("user_token", user_token)
.addFormDataPart("file", file1.toString)//如果还需传递其他字段调用此方法传递
.build();
//创建request对象
Request request = new Request.Builder().url(url).post(multipartBody).build();
okHttpClient.newCall(request)
.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("failed", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String string = response.body().string();
Log.e("shangchuan", string);
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(string);
}
});
}
});
}
}