HttpURLConnection form-data 上传文件
时间: 2023-08-20 12:26:40 浏览: 190
好的,下面是使用HttpURLConnection进行form-data上传文件的步骤:
1. 创建URL对象,指定上传文件的接口地址。
```
URL url = new URL("http://yourserver/upload");
```
2. 创建HttpURLConnection连接对象,并设置请求方法为POST。
```
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
```
3. 设置请求头,指定Content-Type为multipart/form-data。
```
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryxxxxxx");
```
4. 设置请求体,将要上传的文件数据写入请求体中。
```
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes("------WebKitFormBoundaryxxxxxx\r\n");
out.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
out.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
out.write(fileBytes);
out.writeBytes("\r\n------WebKitFormBoundaryxxxxxx--\r\n");
out.flush();
out.close();
```
其中,file是要上传的文件对象,fileBytes是文件的二进制数据。
5. 发送请求并获取响应。
```
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
in.close();
```
以上就是使用HttpURLConnection进行form-data上传文件的步骤,希望能对你有所帮助。
阅读全文
相关推荐


















