java使用原生http发送application/x-www-form-urlencoded请求
时间: 2024-01-19 16:03:08 浏览: 226
使用Java的HttpURLConnection类来发送application/x-www-form-urlencoded请求。以下是一个示例代码:
```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;
public class HttpUrlConnectionExample {
public static void main(String[] args) throws Exception {
String url = "http://www.example.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置POST参数
String title = "test";
String sub1 = "1";
String sub2 = "2";
String sub3 = "3";
String urlParameters = "title=" + URLEncoder.encode(title, "UTF-8") +
"&sub%5B%5D=" + URLEncoder.encode(sub1, "UTF-8") +
"&sub%5B%5D=" + URLEncoder.encode(sub2, "UTF-8") +
"&sub%5B%5D=" + URLEncoder.encode(sub3, "UTF-8");
// 发送POST请求
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// 获取响应结果
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());
}
}
```
阅读全文