post 发送application/x-www-form-urlencoded格式请求 java
时间: 2023-11-08 18:54:47 浏览: 59
在Java中发送application/x-www-form-urlencoded格式的请求,可以使用HttpURLConnection或者HttpClient来实现。下面是使用HttpURLConnection的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Main {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("请求URL");
// 创建HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
// 设置请求头部
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 启用输入输出流
conn.setDoInput(true);
conn.setDoOutput(true);
// 构建请求参数
String params = "param1=" + URLEncoder.encode("value1", "UTF-8") + "¶m2=" + URLEncoder.encode("value2", "UTF-8");
// 发送请求
OutputStream os = conn.getOutputStream();
os.write(params.getBytes("UTF-8"));
os.flush();
// 获取响应结果
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
// 关闭连接和流
reader.close();
os.close();
conn.disconnect();
// 输出响应结果
System.out.println(result.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请将代码中的"请求URL"替换为实际的请求URL,并根据实际情况修改请求参数和响应处理逻辑。