java发送x-www-form-urlencoded
时间: 2023-11-08 12:52:41 浏览: 134
详谈java编码互转(application/x-www-form-urlencoded)
在Java中发送x-www-form-urlencoded数据,你可以使用HttpURLConnection或者HttpClient库进行实现。下面是使用HttpURLConnection的示例代码:
```java
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("https://localhost:8080/poll/query.do");
// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 开启输出流,用于向服务器发送数据
connection.setDoOutput(true);
// 构建请求参数
String params = "customer=123&sign=123";
// 发送请求参数
OutputStream outputStream = connection.getOutputStream();
outputStream.write(params.getBytes());
outputStream.flush();
outputStream.close();
// 获取响应结果
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应结果
System.out.println(response.toString());
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文