url为 http://ip:prot/open/mqm/publish 请求方式为post 如何在java中调接口
时间: 2023-10-10 10:10:25 浏览: 102
您可以使用Java中的HttpURLConnection类来调用这个接口。以下是一个示例:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ApiCaller {
public static void main(String[] args) throws Exception {
String url = "http://ip:port/open/mqm/publish";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("Content-Type", "application/json");
// 设置请求体
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(requestBody.getBytes());
os.flush();
os.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 Code : " + responseCode);
System.out.println("Response Body : " + response.toString());
}
}
```
请注意,这是一个基本示例,您需要根据实际情况进行调整。例如,您需要更改请求头、请求体和响应处理方法。
阅读全文