java 中如何 发送http post请求 并且设置请求和返回内容为GBK格式
时间: 2024-06-09 08:07:43 浏览: 19
在 Java 中发送 HTTP POST 请求并设置请求和返回内容为 GBK 格式,可以使用以下代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpPostDemo {
public static void main(String[] args) {
try {
// 创建 URL 对象
URL url = new URL("http://example.com/api");
// 创建 HttpURLConnection 对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为 POST
conn.setRequestMethod("POST");
// 设置请求头信息
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept-Charset", "GBK");
// 启用输出流,用于向服务器发送数据
conn.setDoOutput(true);
// 创建输出流,并设置编码为 GBK
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "GBK");
// 向服务器发送数据
String data = "param1=value1¶m2=value2";
writer.write(data);
writer.flush();
// 读取服务器返回的数据
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 输出服务器返回的数据
System.out.println(response);
// 关闭输入输出流和连接
reader.close();
writer.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,需要注意以下几点:
1. 在设置请求头信息时,需要设置 Accept-Charset 为 GBK,表示接受服务器返回的 GBK 编码的数据。
2. 在创建输出流时,需要指定编码为 GBK,表示向服务器发送的数据采用 GBK 编码。
3. 在创建输入流时,也需要指定编码为 GBK,表示读取服务器返回的数据采用 GBK 编码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)