java写一个调用post请求json格式带token的
时间: 2023-04-09 22:03:25 浏览: 219
API接口,该怎么写?
你可以使用Java的HttpURLConnection类或者Apache的HttpClient类来实现这个功能。首先,你需要创建一个URL对象,然后使用openConnection()方法打开连接。接下来,设置请求方法为POST,设置请求头中的Content-Type为application/json,设置Authorization头为Bearer加上你的token。最后,将json数据写入请求体中,发送请求并获取响应。具体实现可以参考以下代码:
```
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + token);
String json = "{\"key\":\"value\"}";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(json.getBytes());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
// 处理响应数据
inputStream.close();
}
connection.disconnect();
```
阅读全文