post请求,参数为接口地址,文件的绝对路径,例如:D:/files/a.txt,
返回结构如下:
{"code": 200,"message": "成功","data": "1231312313","ok": true
}
代码如下:
public static String sendFilePost(String url, File file) {trustAllHosts();// 创建OkHttpClient实例OkHttpClient client = new OkHttpClient();// 构建请求体RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.getName(),RequestBody.create(MediaType.parse("application/octet-stream"), file)).build();// 创建POST请求对象Request request = new Request.Builder().url(url).post(requestBody).build();// 发送请求并获取响应try {Response response = client.newCall(request).execute();ObjectMapper objectMapper = new ObjectMapper();// 解析响应体的JSON字符串JsonNode jsonNode = objectMapper.readTree(response.body().string());// 获取data字段的值return jsonNode.get("data").asText();} catch (IOException e) {e.printStackTrace();}return null;}