java httpurlconnection 文件_Java-HttpURLConnection上传文件
时间: 2024-05-15 15:13:55 浏览: 101
Java中使用HttpURLConnection上传文件需要以下步骤:
1. 创建URL对象
```java
URL url = new URL(uploadUrl);
```
2. 创建HttpURLConnection对象
```java
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
```
3. 设置请求方式为POST,设置其他请求头参数
```java
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
```
4. 创建输出流并将数据写入输出流
```java
DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.writeBytes("--" + BOUNDARY + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
outputStream.writeBytes("\r\n");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.writeBytes("\r\n--" + BOUNDARY + "--\r\n");
```
5. 获取响应结果
```java
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
```
完整的代码示例:
```java
public static void uploadFile(File file, String uploadUrl) throws Exception {
String BOUNDARY = "---------------------------123821742118716";
URL url = new URL(uploadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.writeBytes("--" + BOUNDARY + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
outputStream.writeBytes("\r\n");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.writeBytes("\r\n--" + BOUNDARY + "--\r\n");
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
outputStream.close();
fileInputStream.close();
inputStream.close();
conn.disconnect();
}
```
阅读全文