Java发送form-data请求
在Java中,您可以使用HttpURLConnection
或第三方库如Apache HttpClient来发送form-data请求。以下是使用HttpURLConnection
发送form-data的示例代码:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FormDataSender {
public static void sendFormData(String targetUrl, String formData) throws IOException {
// 创建URL对象
URL url = new URL(targetUrl);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求属性,表示是form-data请求
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
// 创建输出流并写入数据
try (OutputStream os = connection.getOutputStream()) {
byte[] outputInBytes = formData.getBytes("UTF-8");
os.write(outputInBytes);
}
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 关闭连接
connection.disconnect();
}
public static void main(String[] args) {
try {
String targetUrl = "http://example.com/submit-form";
String formData = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n" +
"Content-Disposition: form-data; name=\"field1\"\r\n\r\n" +
"value1\
评论已关闭