我正在研究android应用,它将记录音频并使用HttpUrlConnection将base64编码的字符串发送到django服务器。问题是当我按“发送到服务器”应用程序崩溃时。任何人都可以帮助我代码错误的地方。预先感谢您的宝贵时间。
我只想向服务器发送数据
变量
HttpURLConnection connection;
URL urlConnection = new URL("My url");
JSONObject jResponse;
“发送到服务器”按钮的代码
File file = new File(Environment.getExternalStorageDirectory() + "/_audio_record.3gp");
try {
byte[] bytes = FileUtils.readFileToByteArray(file);
encoded = Base64.encodeToString(bytes, NO_WRAP);
Log.i("myApp",encoded);
Toast.makeText(getApplicationContext(),encoded,Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
//Sending json to server
JSONObject param=new JSONObject();
try {
param.put("name",encoded);
} catch (JSONException e) {
e.printStackTrace();
}
makeRequest(param.toString());
makeRequest()
private JSONObject makeRequest(String param) {
try {
HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
connection.setReadTimeout(60000);
connection.setConnectTimeout(60000);
connection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
Log.d("MyApp" ,param);
dataOutputStream.writeBytes(param);
dataOutputStream.flush();
dataOutputStream.close();
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
result.append(line);
}
Log.d("MyApp: ",result.toString());
jResponse = new JSONObject(result.toString());
}
catch (IOException | JSONException e) {
e.printStackTrace();
return jResponse=null;
}
connection.disconnect();
return jResponse;
}