用java写一个可以被调用的post格式的接口
时间: 2024-05-10 07:20:35 浏览: 12
以下是一个使用Java编写的可被调用的POST格式接口的示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
public class PostRequest {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/post";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "application/json");
// 设置POST请求体
String postData = "{\"name\":\"John\",\"age\":30}";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postData);
wr.flush();
wr.close();
// 获取响应码
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 读取响应结果
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.toString());
}
}
```
在上面的示例代码中,我们使用了Java中的HttpURLConnection类来创建了一个POST请求。我们设置了请求方法为POST,请求头包含了User-Agent和Content-Type信息,POST请求体包含了JSON格式的数据。然后我们获取了响应码和响应结果,并将其打印出来。
你可以按照自己的需求修改POST请求体的内容和请求头的信息。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)