最近在调试第三方接口的过程中,发现在发送请求时将本地文件传送给对方结束并结束请求后,本地文件无法删除,依然留存在本地,并且进入到本地文件夹进行手动删除依然无法,只有在项目停止运行才能进行手动删除,查询之后发现该文件无法删除的原因是因为被其他线程占用导致,思来想去在代码中并没有去占用该文件,只有一种可能是在请求过程中没有将文件关闭导致的,说明该请求方式并不适合当前的需求。
原请求方式
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import java.io.File;
public class Demo {
public void requst( String path) {
HttpResponse response = null;
File file = new File(path);
try {
HttpRequest post = HttpUtil.createPost("https://www.****");
//请求参数
post.form("file", file);
//响应值
response = post.execute();
String result = response.body();
//状态码为200时,请求正常
if (200== response.getStatus()) {
System.out.println("成功请求了");
} else {
System.out.println("请求失败了");
}
} catch (Exception e) {
System.out.println(e.getCause().getMessage());
} finally {
//删除本地文件
if (file.exists()&&file!=null){
file.delete();
}
}
}
}
发送请求时其实有很多种方式,以下在该项目中使用的请求方式,无论请求成功或者失败都可以获取对方返回的信息,但是就是无法删除本地文件,查了网上可以使用gc垃圾回收机制强制回收
if(!file.delete){
System.gc();
file.delete;
}
但是在使用gc强制回收时,怕影响原有的垃圾回收机制影响到项目的运行,所以只能探索其他的请求方式,并且能符合我现在的需求
修改后的请求方式
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.File;
@Slf4j
public class Demo {
public void requst( String path) {
File file = new File(path);
//获取文件名,文件格式一般为:D:\**\**.txt,所以从最后一个反斜杠后开始截取
String fileName=path.substring(path.lastIndexOf("/")+1);
OkHttpClient httpClient = new OkHttpClient();
MediaType mediaType = okhttp3.MediaType.parse(org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE);
RequestBody fileBody = RequestBody.create(mediaType, file);
try {
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("meglive_data", fileName,fileBody)
.build();//创建请求参数
Request request = new Request.Builder()
.post(requestBody)
.url("https://www.**")
.build();
Response response = httpClient.newCall(request).execute();
//响应参数
ResponseBody body = response.body();
if (body!=null&& 200== response.code()) {
System.out.println("成功请求了"+body.string());
} else {
System.out.println("请求失败了");
}
} catch (Exception e) {
System.out.println(e.getCause().getMessage());
} finally {
//删除本地文件
if (file.exists()&&file!=null){
file.delete();
}
}
}
}
改完之后成功的删除了文件。请求方式有多种多样,可以自己写,也可以引用其他人写好的工具类,下面为参考网上的大神自己整理的一个get/post请求,作为笔记保存,大家可以忽略
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
public class Demo {
//post请求
public static String doGet(String uri){
HttpURLConnection httpURLConnection=null;
InputStream ipStream=null;
BufferedReader btStream=null;
String result=null;
StringBuffer stringBuffer=null;
try {
URL url = new URL(uri);
httpURLConnection=(HttpURLConnection)url.openConnection();
//设置请求方式
httpURLConnection.setRequestMethod("GET");
//设置连接超时时间
httpURLConnection.setConnectTimeout(3000);
//设置读取远程返回数据超时时间
httpURLConnection.setReadTimeout(6000);
//发送请求连接
httpURLConnection.connect();
//判断请求是否成功
if (httpURLConnection.getResponseCode()==200){
//获取请求结果流
ipStream=httpURLConnection.getInputStream();
btStream=new BufferedReader(new InputStreamReader(ipStream,"utf-8"));
stringBuffer=new StringBuffer();
String temp=null;
while ((temp=btStream.readLine())!=null){
stringBuffer.append(temp);
stringBuffer.append("\r\n");
}
result=stringBuffer.toString();
}else {
httpURLConnection.getResponseCode();
ipStream=httpURLConnection.getErrorStream();
btStream=new BufferedReader(new InputStreamReader(ipStream,"utf-8"));
stringBuffer=new StringBuffer();
String temp=null;
while ((temp=btStream.readLine())!=null){
stringBuffer.append(temp);
stringBuffer.append("\r\n");
}
System.out.println(stringBuffer.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭资源
if (ipStream!=null){
try {
ipStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (btStream!=null){
try {
btStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
httpURLConnection.disconnect();
}
return result;
}
//post请求:
public static String doPost(String uri, Map<String,Object> param){
HttpURLConnection httpURLConnection=null;
InputStream inputStream=null;
BufferedReader bufferedReader=null;
StringBuffer stringBuffer=null;
OutputStream os=null;
String result=null;
try {
URL url = new URL(uri);
httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(6000);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//发送请求连接
httpURLConnection.connect();
// 通过连接对象获取一个输出流
os = httpURLConnection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.toString().getBytes());
//判断请求是否成功
if (httpURLConnection.getResponseCode()==200){
//获取请求结果流
inputStream=httpURLConnection.getInputStream();
bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
stringBuffer=new StringBuffer();
String temp=null;
while ((temp=bufferedReader.readLine())!=null){
stringBuffer.append(temp);
stringBuffer.append("\r\n");
}
result=stringBuffer.toString();
}else {
httpURLConnection.getResponseCode();
inputStream=httpURLConnection.getErrorStream();
bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
stringBuffer=new StringBuffer();
String temp=null;
while ((temp=bufferedReader.readLine())!=null){
stringBuffer.append(temp);
stringBuffer.append("\r\n");
}
//打印错误信息
System.out.println(stringBuffer.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭资源
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
httpURLConnection.disconnect();
}
return result;
}
}
网友评论