我正在制作一个带录音按钮的应用程序和一个将录音文件上传到服务器的按钮。上传按钮应该调用包含okhttp3多部分请求的函数,但是当我单击它时应用程序停止工作。我真的很困惑,因为它与教程完全相同..
以下是与上传按钮相关的代码的一部分。我还在学习如何正确实施请求,请帮助我理解..
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonnn = (Button) findViewById(R.id.buttonnn);
buttonnn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
sendFile();
}});
}
private void sendFile() {
OkHttpClient client = new OkHttpClient();
File f = new File(AudioSavePathInDevice);
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("http://MyServer/thefile.php")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Response error", Toast.LENGTH_LONG).show();
}
}
});
}
gradle文件:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
applicationId "com.android_examples.audiorecording_android_examplescom"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
maven {
url "http://dl.bintray.com/lukaville/maven"
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.squareup.okhttp3:okhttp:3.6.0'
}
编辑:我认为php文件是正确的,因为它正在使用原始项目。但这里是为了使代码更容易阅读。
<?php
$file_path = "images/";
$file_path = $file_path . basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$file_path)) {
echo "success";
}else {
echo "error";
}
?>
就是这样
答案 0 :(得分:0)
尝试更改onFailure
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}