public String upload(String url, File file) throws IOException, JSONException {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("audio", file.getName(),
RequestBody.create(MediaType.parse("audio/wav"), file))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
String res =response.body().string();
System.out.println("服务器返回的结果为:"+res);
JSONObject jsonObject = new JSONObject(res);
String data = jsonObject.getString("result");
System.out.println(data);
Message text = new Message();
text.what = 1;
Bundle bundle = new Bundle();
bundle.putString("word", data);
text.setData(bundle);
handler.sendMessage(text);
return data;
}
}
重点 注意表单数据格式
如果与调用接口的数据格式不一致的话 服务器很可能报出400 BAD REQUEST错误
本文 上传的格式为audio