java发送http formdata请求
时间: 2023-10-07 15:11:59 浏览: 144
java发送http get请求的两种方法(总结)
使用Java发送HTTP FormData请求可以使用Java的HttpURLConnection类。以下是示例代码:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
public class FormDataHttpRequest {
private static final String LINE_FEED = "\r\n";
private static final String BOUNDARY = UUID.randomUUID().toString();
public static void main(String[] args) throws IOException {
String url = "http://example.com/upload";
String charset = "UTF-8";
File textFile = new File("text.txt");
File binaryFile = new File("image.png");
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
try (OutputStream outputStream = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true)) {
// Add text field
writer.append("--").append(BOUNDARY).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"text\"").append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=").append(charset).append(LINE_FEED);
writer.append(LINE_FEED);
writer.append("Text field value").append(LINE_FEED);
writer.flush();
// Add binary file
writer.append("--").append(BOUNDARY).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"")
.append(binaryFile.getName()).append("\"").append(LINE_FEED);
writer.append("Content-Type: ").append(connection.guessContentTypeFromName(binaryFile.getName()))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
Files.copy(binaryFile.toPath(), outputStream);
outputStream.flush();
// End boundary
writer.append(LINE_FEED).append("--").append(BOUNDARY).append("--").append(LINE_FEED);
writer.flush();
}
// Handle response
int responseCode = connection.getResponseCode();
if (responseCode >= 200 && responseCode < 300) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} else {
System.out.println("Request failed with response code " + responseCode);
}
}
}
```
此代码将发送一个HTTP POST请求,其中包含一个文本字段和一个二进制文件。您可以根据需要添加或删除表单字段。注意,此代码将使用Java 7的Files.copy()方法复制二进制文件。如果您使用的是Java 6或更早版本,请使用其他方法复制文件。
阅读全文