原创 

java 上传本地文件并且读取返回结果代码

分类:代码片段    393人阅读    IT小君  2023-03-10 11:25

此结果来自ChatGPT在线:https://yy123.ink/chatgpt

```
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUpload {

public static void main(String[] args) {
String url = "http://example.com/upload";
String filePath = "C:/path/to/file.txt";

try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);

File file = new File(filePath);

OutputStream outputStream = connection.getOutputStream();
outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
reader.close();

System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»