java发送form表单
时间: 2023-09-21 17:04:01 浏览: 46
要使用Java发送form表单,可以使用Java的HttpURLConnection类来模拟HTTP请求并发送form表单数据,以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class FormSubmitter {
public static void main(String[] args) throws Exception {
String url = "http://example.com/submitForm";
String params = "name=" + URLEncoder.encode("张三", "UTF-8") + "&age=18";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(params.getBytes("UTF-8"));
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
```
在上面的示例代码中,我们使用HttpURLConnection类模拟HTTP请求,把form表单数据放在请求体中,然后发送HTTP POST请求。其中,URLEncoder.encode()函数用于对表单数据进行URL编码,防止出现特殊字符导致的请求错误。最后,我们可以读取服务器返回的响应内容并输出到控制台。