java http form提交代码
时间: 2023-10-08 09:14:47 浏览: 99
java发送http/https请求(get/post)代码
4星 · 用户满意度95%
以下是使用Java进行HTTP Form提交的示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpFormSubmit {
public static void main(String[] args) throws Exception {
// 设置URL和请求参数
String url = "http://www.example.com/submitform.php";
Map<String, String> parameters = new HashMap<>();
parameters.put("name", "John Doe");
parameters.put("email", "johndoe@example.com");
parameters.put("message", "Hello, World!");
// 创建连接和请求
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
// 设置请求参数
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
wr.writeBytes(sb.toString());
wr.flush();
wr.close();
// 获取响应
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应
System.out.println(response.toString());
}
}
```
这个示例代码演示了如何使用Java进行HTTP Form提交。它首先设置URL和请求参数,然后创建连接和请求,并将请求参数写入请求体中。最后,它获取响应并打印响应。
阅读全文