源码地址:https://download.csdn.net/download/u013636987/11387400
做这个的时候,我在网上找了很多代码,不是只能上传文件就是只有参数。后面才找到一个可以用的。如下
安卓端
public static void PostFile(File file,Map<String, String> params,String url, final NetComplateListener<String> listener) {
/*****************************************/
// //一种:参数请求体
FormBody.Builder formBody = new FormBody.Builder();
for (String s : params.keySet()) {
System.out.println("key:" + s);
System.out.println("values:" + params.get(s));
formBody.add(s, params.get(s));
}
FormBody paramsBody = formBody.build();
//二种:文件请求体
MediaType type = MediaType.parse("text/plain");//"text/xml;charset=utf-8"
if(!file.exists()) {
Log.e("ldy","文件不存在");
listener.onNetError(-1, "日志文件不存在");
return;
}
RequestBody fileBody = RequestBody.create(type, file);
//三种:混合参数和文件请求
RequestBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.ALTERNATIVE)
//一样的效果
.addPart(Headers.of(
"Content-Disposition",
"form-data; name=\"params\"")
, paramsBody)
.addPart(Headers.of(
"Content-Disposition",
"form-data; name=\"file\"; filename="+file.getName())
, fileBody) .build();
final Request request = new Request.Builder().url(url)
.addHeader("User-Agent", "android")
.header("Content-Type", "text/html; charset=utf-8;")
.post(multipartBody)//传参数、文件或者混合,改一下就行请求体就行
.build();
/****************************************************/
// //创建Request
final OkHttpClient mOkHttpClient = new OkHttpClient();
// final Request request = new Request.Builder().url(url).post(requestBody.build()).build();
final Call call = mOkHttpClient.newBuilder().readTimeout(50, TimeUnit.SECONDS).connectTimeout(50, TimeUnit.SECONDS).writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, e.toString());
listener.onNetError(-1, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String string = response.body().string();
try {
com.alibaba.fastjson.JSONObject returnData = JSON.parseObject(string);
Log.e("ldy","resultCode="+returnData.get("resultCode"));
if (returnData.get("resultCode").toString().equals("0")) {
listener.onNetComplate(returnData.get("resultMsg")+"");
} else {
Log.e("ldy","json="+returnData.toString());
listener.onWorkFlowError("-3",returnData.get("resultMsg")+"");
}
}catch (Exception e)
{
e.printStackTrace();
listener.onWorkFlowError("-4","未知异常");
}
} else {
listener.onNetError(-2, response.message());
}
}
});
}
具体可以看源码里面的codeinput。jar包
然后服务器这么写
public String dealFromPos() {
JSONObject json = new JSONObject();
try {
System.out.println("执行dealFromPos");
request.setCharacterEncoding("UTF-8");
System.out.println("获取Android端传过来的普通信息:");
int sizeThreshold = 10485760;
File repository = new File("/tmp");
// 创建磁盘文件项工厂,参数为缓存文件大小和临时文件位置
DiskFileItemFactory factory = new DiskFileItemFactory(sizeThreshold, repository);
// 创建文件上传核心类
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(10485760);
upload.setSizeMax(10485760);
upload.setHeaderEncoding("UTF-8");
// 判断是否是Multipart类型的
if (ServletFileUpload.isMultipartContent(request)) {
List<FileItem> list = upload.parseRequest(request);
if (list != null) {
for (FileItem item : list) {
// 判断参数是普通参数还是文件参数
if (item.isFormField()) {
// 获得普通参数的key、value(即formData的fileName和fileSize)
String fieldName = item.getFieldName();
String fieldValue = item.getString("UTF-8");
Map<String, String> map = dealParams(fieldValue);
logger.setPos_model(map.get("posModel"));
logger.setSn(map.get("sn"));
logger.setMid(map.get("mid"));
logger.setPid(map.get("pid"));
logger.setFiles_size(map.get("fileSize"));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String Date = sdf.format(new java.util.Date());
logger.setUp_time(Date);
} else {
// 获得文件参数(即formData的file)
String files_name = item.getName();
logger.setFiles_name(files_name);
System.out.println("获取到文件");
String path = FilesUtils.PATHDIR + logger.getSn() + "\\";
String Files_path =FilesUtils.PATHDIR_MYSQL + logger.getSn() + "\\\\" + files_name;
logger.setFiles_path(Files_path);
// 上传文件
uploadFile(item, path, files_name);
}
}
Logger newlogger = loggerService.getBySnAndFileName(logger.getSn(), logger.getFiles_name());
if (newlogger == null) {
loggerService.save(logger);
} else {
logger.setLogger_id(newlogger.getLogger_id());
loggerService.merge(logger);
}
json.put("resultCode", 0);
json.put("resultMsg", "交易成功");
ServletUtils.flushData(response,json.toString());
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
json.put("resultCode", -1);
json.put("resultMsg", "解码失败");
ServletUtils.flushData(response,json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
json.put("resultCode", -2);
json.put("resultMsg", "文件流异常");
ServletUtils.flushData(response,json.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
json.put("resultCode", -3);
json.put("resultMsg", "未知异常");
ServletUtils.flushData(response,json.toString());
}
//
return NONE;
}