Java formdata数据后端如何发送
时间: 2023-05-16 13:05:39 浏览: 231
Java后端可以使用HttpURLConnection或者Apache HttpClient等库来发送formdata数据。以下是使用HttpURLConnection发送formdata数据的示例代码:
```
URL url = new URL("http://example.com/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
String boundary = "---------------------------" + System.currentTimeMillis();
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream outputStream = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"").append("\r\n");
writer.append("Content-Type: text/plain; charset=UTF-8").append("\r\n");
writer.append("\r\n");
writer.flush();
File file = new File("test.txt");
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append("\r\n").flush();
writer.append("--" + boundary + "--").append("\r\n");
writer.close();
outputStream.close();
int responseCode = connection.getResponseCode();
```
在这个示例中,我们使用了HttpURLConnection来发送formdata数据。首先,我们需要设置请求方法为POST,并且设置DoOutput为true,以便我们可以向服务器发送数据。然后,我们设置Content-Type为multipart/form-data,并且指定boundary,boundary是一个随机字符串,用于分隔不同的formdata字段。接下来,我们获取输出流,并且使用PrintWriter来写入formdata数据。在这个示例中,我们只上传了一个名为test.txt的文件,我们首先写入文件的Content-Disposition和Content-Type信息,然后写入文件的内容。最后,我们写入一个结束标记--boundary--,并且关闭输出流。最后,我们可以获取服务器的响应码。
阅读全文