更新时间:2024-11-21 GMT+08:00
媒体文件删除
代码样例
import static java.nio.charset.StandardCharsets.UTF_8; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * 媒体文件删除样例 */ public final class FileDelete { // 带有值的返回成功状态码 static final int SUCCESS_200_RES = 200; // 不带值的返回成功状态码 static final int SUCCESS_204_RES = 204; private FileDelete() { } /** * 媒体文件删除 * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Logger logger = Logger.getLogger(SendMsg.class.getName()); logger.setLevel(Level.WARNING); String url = "http://127.0.0.1:8323/openchatbot/v2/sip:chatbotid32test1@botplatform.rcs.chinamobile.com/files"; URL realUrl = new URL(url); Map<String, Object> map = new HashMap<>(); // 媒体删除文件要依据tid map.put("tid", "1234567890123459"); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); // 设置可输入 connection.setDoInput(true); // 设置该连接是可以输出的 connection.setDoOutput(true); // 设置请求方式 connection.setRequestMethod("DELETE"); connection.setRequestProperty("Authorization", "Username=\"appId32test1\",Password=\"******\""); connection.setRequestProperty("X-WSSE", "UsernameToken Username=\"appId32test1\""); ObjectMapper objectMapper = new ObjectMapper(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), UTF_8)); pw.write(objectMapper.writeValueAsString(map)); pw.flush(); // 关流操作,这个很重要 pw.close(); connection.connect(); int status = connection.getResponseCode(); logger.warning("DELETE status: " + status); InputStream is; if (status != SUCCESS_200_RES) { if (status == SUCCESS_204_RES) { logger.warning("No Content, Success"); is = connection.getInputStream(); } else { // 400/401 logger.warning("Error, DELETE status: " + status); is = connection.getErrorStream(); } } else { // 200 logger.warning("OK,DELETE Success, DELETE status: " + status); is = connection.getInputStream(); } if (is != null) { BufferedReader br; br = new BufferedReader(new InputStreamReader(is, UTF_8)); String line; StringBuilder result = new StringBuilder(); // 读取数据 while ((line = br.readLine()) != null) { result.append(line + System.lineSeparator().intern()); } br.close(); // 关流操作,这个很重要 is.close(); // 关闭连接 connection.disconnect(); logger.warning("Content: " + result.toString()); } } }
参数名称 |
参数说明 |
---|---|
url |
请求地址 |
Map |
封装请求发送的信息、参数 |
Connection |
封装建立连接的认证信息、请求方式等 |
消息样例
DELETE status:200
OK,DELETE请求成功,响应消息有消息体。
响应消息(可能消息体存在但是为空)。
父主题: JAVA