java 发送form-data请求代码
时间: 2023-06-01 12:06:32 浏览: 193
好的,以下是一个使用Java发送form-data请求的代码示例:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
public class FormDataRequestExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/submitform";
Map<String, String> formData = new LinkedHashMap<>();
formData.put("firstname", "John");
formData.put("lastname", "Doe");
formData.put("email", "johndoe@example.com");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// Set content-type header for form data
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Build form data string
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : formData.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(param.getKey());
postData.append('=');
postData.append(param.getValue());
}
// Send form data
con.setDoOutput(true);
con.getOutputStream().write(postData.toString().getBytes("UTF-8"));
// Read response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print response
System.out.println(response.toString());
}
}
```
该代码创建了一个 `Map<String, String>` 对象,里面存储了表单数据。然后使用 `HttpURLConnection` 将请求发送到指定的 URL。在请求头中使用 `Content-Type` 指定请求体类型为 `application/x-www-form-urlencoded`。同时,使用 StringBuilder 构建表单数据字符串,并将其作为请求体发送。最后,读取响应并输出。
请注意,该代码示例适用于普通的 form-data 请求,不适用于上传文件等更复杂的场景。如果需要上传文件,请参考其他资料。
阅读全文