#android端
okhttp的项目地址github
private void asyncSendFile(String filename){//在子线程中实现网络操作,传入文件名
//获取文件夹
String filepath = Environment.getExternalStorageDirectory().getPath() + "/temp";
File file = new File(filepath, filename);
//文件夹存在,文件存在开启新线程进行传输
if(file.exists() && file.isFile()){
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");//设置头信息
//新建请求
RequestBody requestBody = RequestBody.create(wavfile, mediaType);
Request request = new Request.Builder()
.url(url_file)
.post(requestBody).build();
//发起请求,并重写回调函数
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
showLogMsg(LoginActivity.this, 0, "请求服务器失败:"+e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//获取回复消息,使用json形式处理
String resData = response.body().string();
try {
JSONArray jsonArray = new JSONArray(resData);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String sendOk = jsonObject.getString("sendOk");
if(sendOk.equals("true")){
Snackbar.make(getWindow().getDecorView(), "发送成功", Snackbar.LENGTH_SHORT).show();
}else{
Snackbar.make(getWindow().getDecorView(), "发送失败", Snackbar.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}else{
Toast.makeText(LoginActivity.this, "录制失败,请重新尝试", Toast.LENGTH_SHORT).show();
}
}
#服务器端servlet实现
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
ServletInputStream is = request.getInputStream();
String filepath = "E:/";
String filename = "1.txt"
File file0 = new File(filepath);
if(!file0.exists()) {
file0.mkdirs();
}
File file = new File(filepath, filename);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
fos.close();
JSONArray jsonArray3 = new JSONArray();
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("sendOk", "true");
jsonArray3.add(jsonObject3);
PrintWriter out = response.getWriter();
out.println(jsonArray3);
}