java开发post请求查询接口
时间: 2023-10-06 12:07:00 浏览: 63
你可以使用 Java 的 HttpURLConnection 或者 Apache HttpClient 来发送 POST 请求查询接口。以下是使用 HttpURLConnection 的示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostRequestExample {
public static void main(String[] args) throws IOException {
// 请求URL
String url = "https://example.com/api/query";
// 请求参数
String query = "param1=value1¶m2=value2";
// 创建连接
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 启用输入和输出流
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置请求头信息
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 发送请求
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(query);
outputStream.flush();
outputStream.close();
// 获取响应结果
int responseCode = connection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response: " + response.toString());
}
}
```
在上述代码中,你需要替换 `url` 变量为你要请求的接口 URL,`query` 变量为请求参数。根据实际情况,你可能还需要设置其他请求头信息和处理不同的响应结果。
使用 Apache HttpClient 的方式类似,你可以参考 HttpClient 的文档和示例代码来实现 POST 请求查询接口。