OC中的connection 和 session

本文对比了苹果系统中两种网络请求方法:connection 和 session。connection 是早期使用的方案,支持 GET 和 POST 请求,以及同步和异步操作;session 则是当前推荐的方法,提供代码块和代理两种实现方式。

connection 是苹果以前使用的网络请求,

但现在还有一部分软件使用connection,

分为 get 和 post,还有同步和异步两种状态



session  是苹果现阶段推荐使用的的网络请求方法,

有 代码块 和 代理 两种方法可以实现


<?php namespace OCA\IdCardQuery\Controller; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\DataResponse; use OCP\IDBConnection; use OCP\IRequest; use OCP\ISession; use OCP\IUserSession; use OCP\Security\ISecureRandom; class IdCardApiController extends Controller { private $db; private $session; private $userSession; private $random; public function __construct($appName, IRequest $request, IDBConnection $db, ISession $session, IUserSession $userSession, ISecureRandom $random) { parent::__construct($appName, $request); $this->db = $db; $this->session = $session; $this->userSession = $userSession; $this->random = $random; } /** * @NoCSRFRequired * @PublicPage */ public function loginByIdCard(string $idCard, string $apiKey) { // 1. 验证API密钥 if (!$this->validateApiKey($apiKey)) { return new DataResponse(['error' => 'Invalid API key'], 401); } // 2. 查询用户 $user = $this->getUserByIdCard($idCard); if (!$user) { return new DataResponse(['error' => 'User not found'], 404); } // 3. 创建登录会话 $loginData = $this->createLoginSession($user['uid']); //$sessionCookie = $this->session->get($user['uid']); // 获取会话Cookie名(默认nc_sid) //$sessionId = $this->session->getId(); // 获取会话ID //$cookieParams = session_get_cookie_params(); // 获取Cookie参数(过期时间、路径等) return new DataResponse([ 'status' => 'success', 'user_id' => $user['uid'], 'official_session' => [ 'cookie_name' => $sessionCookie, 'cookie_value' => $sessionId, 'expires' => $cookieParams['lifetime'] ?: time() + 3600, 'path' => $cookieParams['path'], 'domain' => $cookieParams['domain'], 'secure' => $cookieParams['secure'], 'httponly' => $cookieParams['httponly'] ], 'session_token' => $loginData['token'], 'login_name' => $user['uid'], // Nextcloud用户名 'display_name' => $user['displayname'], 'expires' => time() + 3600 // 1小时有效期 ]); } private function validateApiKey(string $apiKey): bool { // 从配置中获取有效API密钥 (实际使用应存储到config.php) $validKey = \OC::$server->getConfig()->getAppValue('your_app', 'api_key', ''); return hash_equals($validKey, $apiKey); } private function getUserByIdCard(string $idCard): ?array { $query = $this->db->getQueryBuilder(); $query->select('uid', 'displayname') ->from('users') ->where($query->expr()->eq('id_card', $query->createNamedParameter($idCard))) ->setMaxResults(1); $result = $query->execute(); $data = $result->fetch(); $result->closeCursor(); return $data ?: null; } private function createLoginSession(string $userId): array { // 生成随机令牌 $token = $this->random->generate(64); // 保存到会话 $this->session->set('user_id', $userId); $this->session->set('login_token', $token); // 实际登录用户 $user = \OC::$server->getUserManager()->get($userId); $this->userSession->setUser($user); return ['token' => $token]; } }这是我的api代码,以下是我的jsp页面代码,请结合我刚才的问题重新回答<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.net.HttpURLConnection" %> <%@ page import="java.net.URL" %> <%@ page import="java.net.URLEncoder" %> <%@ page import="java.io.BufferedReader" %> <%@ page import="java.io.InputStreamReader" %> <%@ page import="java.io.InputStream" %> <%@ page import="java.io.OutputStream" %> <%@ page import="java.util.Scanner" %> <% // 1. 配置接口参数(可根据实际需求从前端获取,此处为固定示例) String idCard = "330327200001010002"; String apiKey = ""; // 替换为你实际配置的API密钥 String nextcloudApiUrl = "http://172.17.0.1:10081/index.php/apps/idcardquery/api/get_user_by_idcard"; // 拼接GET请求参数并做URL编码,避免特殊字符导致请求异常 String queryParams = "?idCard=" + URLEncoder.encode(idCard, "UTF-8") + "&apiKey=" + URLEncoder.encode(apiKey, "UTF-8"); String fullApiUrl = nextcloudApiUrl + queryParams; // 2. 初始化变量 HttpURLConnection connection = null; BufferedReader reader = null; String responseJsonStr = ""; String errorMsg = ""; try { // 创建URL对象 URL url = new URL(fullApiUrl); connection = (HttpURLConnection) url.openConnection(); // 设置请求配置 connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setConnectTimeout(10000); // 连接超时5秒 connection.setReadTimeout(10000); // 读取超时5秒 connection.setDoInput(true); // 3. 获取响应码并处理响应 int responseCode = connection.getResponseCode(); InputStream inputStream = null; if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功,获取正常响应流 inputStream = connection.getInputStream(); } else { // 请求失败,获取错误响应流 inputStream = connection.getErrorStream(); errorMsg = "接口请求失败,响应码:" + responseCode; } // 读取响应数据(兼容各种编码格式) reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } responseJsonStr = sb.toString(); // 若请求失败,直接输出错误信息并终止 if (!errorMsg.isEmpty()) { out.print(errorMsg + ",错误详情:" + responseJsonStr); return; } // 跳转Nextcloud主页 response.sendRedirect("http://192.168.177.116:10081/index.php/apps/files/"); } catch (Exception e) { // 异常处理 out.print("接口调用异常:" + e.getMessage()); e.printStackTrace(); } finally { // 关闭资源,避免内存泄漏 if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } %>
最新发布
12-26
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.net.HttpURLConnection" %> <%@ page import="java.net.URL" %> <%@ page import="java.net.URLEncoder" %> <%@ page import="java.io.BufferedReader" %> <%@ page import="java.io.InputStreamReader" %> <%@ page import="java.io.InputStream" %> <%@ page import="java.io.OutputStream" %> <%@ page import="java.util.Scanner" %> <% // 1. 配置接口参数(可根据实际需求从前端获取,此处为固定示例) String idCard = "330327200001010002"; String apiKey = ""; // 替换为你实际配置的API密钥 String nextcloudApiUrl = "http://172.17.0.1:10081/index.php/apps/idcardquery/api/get_user_by_idcard"; // 拼接GET请求参数并做URL编码,避免特殊字符导致请求异常 String queryParams = "?idCard=" + URLEncoder.encode(idCard, "UTF-8") + "&apiKey=" + URLEncoder.encode(apiKey, "UTF-8"); String fullApiUrl = nextcloudApiUrl + queryParams; // 2. 初始化变量 HttpURLConnection connection = null; BufferedReader reader = null; String responseJsonStr = ""; String errorMsg = ""; try { // 创建URL对象 URL url = new URL(fullApiUrl); connection = (HttpURLConnection) url.openConnection(); // 设置请求配置 connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setConnectTimeout(10000); // 连接超时5秒 connection.setReadTimeout(10000); // 读取超时5秒 connection.setDoInput(true); // 3. 获取响应码并处理响应 int responseCode = connection.getResponseCode(); InputStream inputStream = null; if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功,获取正常响应流 inputStream = connection.getInputStream(); } else { // 请求失败,获取错误响应流 inputStream = connection.getErrorStream(); errorMsg = "接口请求失败,响应码:" + responseCode; } // 读取响应数据(兼容各种编码格式) reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } responseJsonStr = sb.toString(); // 若请求失败,直接输出错误信息并终止 if (!errorMsg.isEmpty()) { out.print(errorMsg + ",错误详情:" + responseJsonStr); return; } // 4. 手动解析JSON(避免依赖org.json包,使用字符串截取简化解析,若需完整JSON解析可使用JDK自带的JsonReader) // 简化版:假设接口返回格式固定,直接截取关键参数(若需要更严谨的JSON解析,可参考JDK 11+的javax.json API) // 实际生产环境中,若JDK版本≥11,可使用javax.json(自带,无需额外JAR) String status = ""; String cookieName = ""; String cookieid = ""; long expires = System.currentTimeMillis() + 3600 * 1000; String path = "/"; String domain = ""; boolean secure = false; boolean httponly = true; // 简单截取(仅适用于固定格式的JSON响应,若响应格式复杂,建议使用JDK自带JSON API) if (json.contains("\"status\":\"success\"")) { // 使用正则表达式提取值(改进版,更健壮) String sessionName = extractValue(json, "session", "name"); String sessionId = extractValue(json, "session", "id"); String expires = extractValue(json, "session", "expires"); String path = extractValue(json, "session", "path"); String domain = extractValue(json, "session", "domain"); String secure = extractValue(json, "session", "secure"); String httponly = extractValue(json, "session", "httponly"); String samesite = extractValue(json, "session", "samesite"); // 计算最大生存时间(秒) long currentTime = System.currentTimeMillis() / 1000; long expireTime = Long.parseLong(expires); int maxAge = (int) (expireTime - currentTime); if (maxAge < 0) maxAge = 0; // 创建会话Cookie createCookie(response, sessionName, sessionId, domain, path, maxAge, "true".equals(secure), "true".equals(httponly), samesite); // 创建其他必要Cookie - 注意:这些值应该从API响应中获取,这里示例使用固定值 createCookie(response, "nc_username", "nextcloud", domain, "/", maxAge, true, true, "None"); // 注意:oc_sessionPassphrase的值应该从API响应中获取,这里示例使用固定值(实际中需要替换) createCookie(response, "oc_sessionPassphrase", "%2Fo9aCFa3pSMEUr8DJvF%2BAooySI3mrG44bVDTknPyCsuZIOUFWqA%2F498ocjSj5YCfZWCersauEkq3QUKNLSwcvsqAE%2F%2BMuC%2BOxA3dTNXb7JgJ4L%2Bu1CNZzTUmykTWuqBm", domain, "/", maxAge, true, true, "None"); // 重定向到Nextcloud(使用绝对URL,HTTPS) response.sendRedirect(nextcloudRedirectUrl); } else { // 登录失败,输出错误信息 out.print("登录失败:" + (errorMsg.isEmpty() ? "未知错误" : errorMsg)); } } catch (Exception e) { // 异常处理 out.print("接口调用异常:" + e.getMessage()); e.printStackTrace(); } finally { // 关闭资源,避免内存泄漏 if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } %> <%! // 创建Cookie的辅助方法 private void createCookie(jakarta.servlet.http.HttpServletResponse response, String name, String value, String domain, String path, int maxAge, boolean secure, boolean httpOnly, String sameSite) { Cookie cookie = new Cookie(name, value); if (path != null && !path.isEmpty()) { cookie.setPath(path); } else { cookie.setPath("/"); } cookie.setMaxAge(maxAge); cookie.setSecure(secure); cookie.setHttpOnly(httpOnly); // 设置SameSite属性(Servlet 4.0+) if (sameSite != null) { cookie.setAttribute("SameSite", sameSite); } // 如果指定了域名,则设置 if (domain != null && !domain.isEmpty()) { cookie.setDomain(domain); } response.addCookie(cookie); } // JSON解析辅助方法(改进版,处理带引号不带引号的值) private String extractValue(String json, String parent, String key) { // 尝试匹配: "parent": { ... "key": "value" ... } Pattern pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*\"([^\"]*)\"[^}]*\\}"); Matcher matcher = pattern.matcher(json); if (matcher.find()) { return matcher.group(1); } // 尝试匹配: "parent": { ... "key": value ... } (值没有引号) pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*([^,}]+)[^}]*\\}"); matcher = pattern.matcher(json); if (matcher.find()) { return matcher.group(1); } return null; } // 提取错误消息 private String extractValue(String json, String key) { Pattern pattern = Pattern.compile("\""+key+"\"\\s*:\\s*\"([^\"]*)\""); Matcher matcher = pattern.matcher(json); if (matcher.find()) { return matcher.group(1); } return null; } %>运行后抛出异常HTTP状态 500 - 内部服务器错误 类型 异常报告 消息 org.apache.jasper.JasperException: Unable to compile class for JSP: 描述 服务器遇到一个意外的情况,阻止它完成请求。 例外情况 org.apache.jasper.JasperException: org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: [166] in the jsp file: [/index.jsp] Pattern cannot be resolved to a type 163: // JSON解析辅助方法(改进版,处理带引号不带引号的值) 164: private String extractValue(String json, String parent, String key) { 165: // 尝试匹配: "parent": { ... "key": "value" ... } 166: Pattern pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*\"([^\"]*)\"[^}]*\\}"); 167: Matcher matcher = pattern.matcher(json); 168: if (matcher.find()) { 169: return matcher.group(1); An error occurred at line: [166] in the jsp file: [/index.jsp] Pattern cannot be resolved 163: // JSON解析辅助方法(改进版,处理带引号不带引号的值) 164: private String extractValue(String json, String parent, String key) { 165: // 尝试匹配: "parent": { ... "key": "value" ... } 166: Pattern pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*\"([^\"]*)\"[^}]*\\}"); 167: Matcher matcher = pattern.matcher(json); 168: if (matcher.find()) { 169: return matcher.group(1); An error occurred at line: [167] in the jsp file: [/index.jsp] Matcher cannot be resolved to a type 164: private String extractValue(String json, String parent, String key) { 165: // 尝试匹配: "parent": { ... "key": "value" ... } 166: Pattern pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*\"([^\"]*)\"[^}]*\\}"); 167: Matcher matcher = pattern.matcher(json); 168: if (matcher.find()) { 169: return matcher.group(1); 170: } An error occurred at line: [172] in the jsp file: [/index.jsp] Pattern cannot be resolved 169: return matcher.group(1); 170: } 171: // 尝试匹配: "parent": { ... "key": value ... } (值没有引号) 172: pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*([^,}]+)[^}]*\\}"); 173: matcher = pattern.matcher(json); 174: if (matcher.find()) { 175: return matcher.group(1); An error occurred at line: [182] in the jsp file: [/index.jsp] Pattern cannot be resolved to a type 179: 180: // 提取错误消息 181: private String extractValue(String json, String key) { 182: Pattern pattern = Pattern.compile("\""+key+"\"\\s*:\\s*\"([^\"]*)\""); 183: Matcher matcher = pattern.matcher(json); 184: if (matcher.find()) { 185: return matcher.group(1); An error occurred at line: [182] in the jsp file: [/index.jsp] Pattern cannot be resolved 179: 180: // 提取错误消息 181: private String extractValue(String json, String key) { 182: Pattern pattern = Pattern.compile("\""+key+"\"\\s*:\\s*\"([^\"]*)\""); 183: Matcher matcher = pattern.matcher(json); 184: if (matcher.find()) { 185: return matcher.group(1); An error occurred at line: [183] in the jsp file: [/index.jsp] Matcher cannot be resolved to a type 180: // 提取错误消息 181: private String extractValue(String json, String key) { 182: Pattern pattern = Pattern.compile("\""+key+"\"\\s*:\\s*\"([^\"]*)\""); 183: Matcher matcher = pattern.matcher(json); 184: if (matcher.find()) { 185: return matcher.group(1); 186: } An error occurred at line: [81] in the jsp file: [/index.jsp] json cannot be resolved 78: boolean httponly = true; 79: 80: // 简单截取(仅适用于固定格式的JSON响应,若响应格式复杂,建议使用JDK自带JSON API) 81: if (json.contains("\"status\":\"success\"")) { 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); An error occurred at line: [83] in the jsp file: [/index.jsp] json cannot be resolved to a variable 80: // 简单截取(仅适用于固定格式的JSON响应,若响应格式复杂,建议使用JDK自带JSON API) 81: if (json.contains("\"status\":\"success\"")) { 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); An error occurred at line: [84] in the jsp file: [/index.jsp] json cannot be resolved to a variable 81: if (json.contains("\"status\":\"success\"")) { 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); An error occurred at line: [85] in the jsp file: [/index.jsp] Duplicate local variable expires 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); An error occurred at line: [85] in the jsp file: [/index.jsp] json cannot be resolved to a variable 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); An error occurred at line: [86] in the jsp file: [/index.jsp] Duplicate local variable path 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); An error occurred at line: [86] in the jsp file: [/index.jsp] json cannot be resolved to a variable 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); An error occurred at line: [87] in the jsp file: [/index.jsp] Duplicate local variable domain 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); An error occurred at line: [87] in the jsp file: [/index.jsp] json cannot be resolved to a variable 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); An error occurred at line: [88] in the jsp file: [/index.jsp] Duplicate local variable secure 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: An error occurred at line: [88] in the jsp file: [/index.jsp] json cannot be resolved to a variable 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: An error occurred at line: [89] in the jsp file: [/index.jsp] Duplicate local variable httponly 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: 92: // 计算最大生存时间(秒) An error occurred at line: [89] in the jsp file: [/index.jsp] json cannot be resolved to a variable 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: 92: // 计算最大生存时间(秒) An error occurred at line: [90] in the jsp file: [/index.jsp] json cannot be resolved to a variable 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: 92: // 计算最大生存时间(秒) 93: long currentTime = System.currentTimeMillis() / 1000; An error occurred at line: [110] in the jsp file: [/index.jsp] nextcloudRedirectUrl cannot be resolved to a variable 107: domain, "/", maxAge, true, true, "None"); 108: 109: // 重定向到Nextcloud(使用绝对URL,HTTPS) 110: response.sendRedirect(nextcloudRedirectUrl); 111: } else { 112: // 登录失败,输出错误信息 113: out.print("登录失败:" + (errorMsg.isEmpty() ? "未知错误" : errorMsg)); Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:547) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:394) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:330) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:281) jakarta.servlet.http.HttpServlet.service(HttpServlet.java:710) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) 根本原因。 org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: [166] in the jsp file: [/index.jsp] Pattern cannot be resolved to a type 163: // JSON解析辅助方法(改进版,处理带引号不带引号的值) 164: private String extractValue(String json, String parent, String key) { 165: // 尝试匹配: "parent": { ... "key": "value" ... } 166: Pattern pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*\"([^\"]*)\"[^}]*\\}"); 167: Matcher matcher = pattern.matcher(json); 168: if (matcher.find()) { 169: return matcher.group(1); An error occurred at line: [166] in the jsp file: [/index.jsp] Pattern cannot be resolved 163: // JSON解析辅助方法(改进版,处理带引号不带引号的值) 164: private String extractValue(String json, String parent, String key) { 165: // 尝试匹配: "parent": { ... "key": "value" ... } 166: Pattern pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*\"([^\"]*)\"[^}]*\\}"); 167: Matcher matcher = pattern.matcher(json); 168: if (matcher.find()) { 169: return matcher.group(1); An error occurred at line: [167] in the jsp file: [/index.jsp] Matcher cannot be resolved to a type 164: private String extractValue(String json, String parent, String key) { 165: // 尝试匹配: "parent": { ... "key": "value" ... } 166: Pattern pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*\"([^\"]*)\"[^}]*\\}"); 167: Matcher matcher = pattern.matcher(json); 168: if (matcher.find()) { 169: return matcher.group(1); 170: } An error occurred at line: [172] in the jsp file: [/index.jsp] Pattern cannot be resolved 169: return matcher.group(1); 170: } 171: // 尝试匹配: "parent": { ... "key": value ... } (值没有引号) 172: pattern = Pattern.compile("\""+parent+"\":\\s*\\{[^}]*\""+key+"\"\\s*:\\s*([^,}]+)[^}]*\\}"); 173: matcher = pattern.matcher(json); 174: if (matcher.find()) { 175: return matcher.group(1); An error occurred at line: [182] in the jsp file: [/index.jsp] Pattern cannot be resolved to a type 179: 180: // 提取错误消息 181: private String extractValue(String json, String key) { 182: Pattern pattern = Pattern.compile("\""+key+"\"\\s*:\\s*\"([^\"]*)\""); 183: Matcher matcher = pattern.matcher(json); 184: if (matcher.find()) { 185: return matcher.group(1); An error occurred at line: [182] in the jsp file: [/index.jsp] Pattern cannot be resolved 179: 180: // 提取错误消息 181: private String extractValue(String json, String key) { 182: Pattern pattern = Pattern.compile("\""+key+"\"\\s*:\\s*\"([^\"]*)\""); 183: Matcher matcher = pattern.matcher(json); 184: if (matcher.find()) { 185: return matcher.group(1); An error occurred at line: [183] in the jsp file: [/index.jsp] Matcher cannot be resolved to a type 180: // 提取错误消息 181: private String extractValue(String json, String key) { 182: Pattern pattern = Pattern.compile("\""+key+"\"\\s*:\\s*\"([^\"]*)\""); 183: Matcher matcher = pattern.matcher(json); 184: if (matcher.find()) { 185: return matcher.group(1); 186: } An error occurred at line: [81] in the jsp file: [/index.jsp] json cannot be resolved 78: boolean httponly = true; 79: 80: // 简单截取(仅适用于固定格式的JSON响应,若响应格式复杂,建议使用JDK自带JSON API) 81: if (json.contains("\"status\":\"success\"")) { 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); An error occurred at line: [83] in the jsp file: [/index.jsp] json cannot be resolved to a variable 80: // 简单截取(仅适用于固定格式的JSON响应,若响应格式复杂,建议使用JDK自带JSON API) 81: if (json.contains("\"status\":\"success\"")) { 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); An error occurred at line: [84] in the jsp file: [/index.jsp] json cannot be resolved to a variable 81: if (json.contains("\"status\":\"success\"")) { 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); An error occurred at line: [85] in the jsp file: [/index.jsp] Duplicate local variable expires 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); An error occurred at line: [85] in the jsp file: [/index.jsp] json cannot be resolved to a variable 82: // 使用正则表达式提取值(改进版,更健壮) 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); An error occurred at line: [86] in the jsp file: [/index.jsp] Duplicate local variable path 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); An error occurred at line: [86] in the jsp file: [/index.jsp] json cannot be resolved to a variable 83: String sessionName = extractValue(json, "session", "name"); 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); An error occurred at line: [87] in the jsp file: [/index.jsp] Duplicate local variable domain 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); An error occurred at line: [87] in the jsp file: [/index.jsp] json cannot be resolved to a variable 84: String sessionId = extractValue(json, "session", "id"); 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); An error occurred at line: [88] in the jsp file: [/index.jsp] Duplicate local variable secure 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: An error occurred at line: [88] in the jsp file: [/index.jsp] json cannot be resolved to a variable 85: String expires = extractValue(json, "session", "expires"); 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: An error occurred at line: [89] in the jsp file: [/index.jsp] Duplicate local variable httponly 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: 92: // 计算最大生存时间(秒) An error occurred at line: [89] in the jsp file: [/index.jsp] json cannot be resolved to a variable 86: String path = extractValue(json, "session", "path"); 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: 92: // 计算最大生存时间(秒) An error occurred at line: [90] in the jsp file: [/index.jsp] json cannot be resolved to a variable 87: String domain = extractValue(json, "session", "domain"); 88: String secure = extractValue(json, "session", "secure"); 89: String httponly = extractValue(json, "session", "httponly"); 90: String samesite = extractValue(json, "session", "samesite"); 91: 92: // 计算最大生存时间(秒) 93: long currentTime = System.currentTimeMillis() / 1000; An error occurred at line: [110] in the jsp file: [/index.jsp] nextcloudRedirectUrl cannot be resolved to a variable 107: domain, "/", maxAge, true, true, "None"); 108: 109: // 重定向到Nextcloud(使用绝对URL,HTTPS) 110: response.sendRedirect(nextcloudRedirectUrl); 111: } else { 112: // 登录失败,输出错误信息 113: out.print("登录失败:" + (errorMsg.isEmpty() ? "未知错误" : errorMsg)); Stacktrace: org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:70) org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:189) org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:523) org.apache.jasper.compiler.Compiler.compile(Compiler.java:367) org.apache.jasper.compiler.Compiler.compile(Compiler.java:339) org.apache.jasper.compiler.Compiler.compile(Compiler.java:325) org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:585) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:368) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:330) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:281) jakarta.servlet.http.HttpServlet.service(HttpServlet.java:710) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ):注意 主要问题的全部 stack 信息可以在 server logs 里查看 Apache Tomcat/11.0.15
12-26
<?php namespace OCA\IdCardQuery\Controller; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\DataResponse; use OCP\IDBConnection; use OCP\IRequest; use OCP\ISession; use OCP\IUserSession; use OCP\Security\ISecureRandom; class IdCardApiController extends Controller { private $db; private $session; private $userSession; private $random; public function __construct($appName, IRequest $request, IDBConnection $db, ISession $session, IUserSession $userSession, ISecureRandom $random) { parent::__construct($appName, $request); $this->db = $db; $this->session = $session; $this->userSession = $userSession; $this->random = $random; } /** * @NoCSRFRequired * @PublicPage */ public function loginByIdCard(string $idCard, string $apiKey) { // 1. 验证API密钥 if (!$this->validateApiKey($apiKey)) { return new DataResponse(['error' => 'Invalid API key'], 401); } // 2. 查询用户 $user = $this->getUserByIdCard($idCard); if (!$user) { return new DataResponse(['error' => 'User not found'], 404); } // 3. 创建登录会话 $loginData = $this->createLoginSession($user['uid']); $sessionId = $this->session->getId(); $cookieParams = session_get_cookie_params(); //$sessionCookie = $this->session->get($user['uid']); // 获取会话Cookie名(默认nc_sid) //$sessionId = $this->session->getId(); // 获取会话ID //$cookieParams = session_get_cookie_params(); // 获取Cookie参数(过期时间、路径等) return new DataResponse([ 'status' => 'success', 'user_id' => $user['uid'], 'official_session' => [ 'name' => session_name(), 'id' => session_id(), 'expires' => $cookieParams['lifetime'] ?: time() + 3600, 'path' => $cookieParams['path'], 'domain' => $cookieParams['domain'], 'secure' => $cookieParams['secure'], 'httponly' => $cookieParams['httponly'] ], 'session_token' => $loginData['token'], 'login_name' => $user['uid'], // Nextcloud用户名 'display_name' => $user['displayname'], 'expires' => time() + 3600 // 1小时有效期 ]); } private function validateApiKey(string $apiKey): bool { // 从配置中获取有效API密钥 (实际使用应存储到config.php) $validKey = \OC::$server->getConfig()->getAppValue('your_app', 'api_key', ''); return hash_equals($validKey, $apiKey); } private function getUserByIdCard(string $idCard): ?array { $query = $this->db->getQueryBuilder(); $query->select('uid', 'displayname') ->from('users') ->where($query->expr()->eq('id_card', $query->createNamedParameter($idCard))) ->setMaxResults(1); $result = $query->execute(); $data = $result->fetch(); $result->closeCursor(); return $data ?: null; } private function createLoginSession(string $userId): array { // 生成随机令牌 $token = $this->random->generate(64); // 保存到会话 $this->session->set('user_id', $userId); $this->session->set('login_token', $token); // 实际登录用户 $user = \OC::$server->getUserManager()->get($userId); $this->userSession->setUser($user); return ['token' => $token]; } } 这是我的API代码,以下是我的jsp页面代码,<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.net.HttpURLConnection" %> <%@ page import="java.net.URL" %> <%@ page import="java.net.URLEncoder" %> <%@ page import="java.io.BufferedReader" %> <%@ page import="java.io.InputStreamReader" %> <%@ page import="java.io.InputStream" %> <%@ page import="java.io.OutputStream" %> <%@ page import="java.util.Scanner" %> <% // 1. 配置接口参数(可根据实际需求从前端获取,此处为固定示例) String idCard = "330327200001010002"; String apiKey = ""; // 替换为你实际配置的API密钥 String nextcloudApiUrl = "http://172.17.0.1:10081/index.php/apps/idcardquery/api/get_user_by_idcard"; // 拼接GET请求参数并做URL编码,避免特殊字符导致请求异常 String queryParams = "?idCard=" + URLEncoder.encode(idCard, "UTF-8") + "&apiKey=" + URLEncoder.encode(apiKey, "UTF-8"); String fullApiUrl = nextcloudApiUrl + queryParams; // 2. 初始化变量 HttpURLConnection connection = null; BufferedReader reader = null; String responseJsonStr = ""; String errorMsg = ""; try { // 创建URL对象 URL url = new URL(fullApiUrl); connection = (HttpURLConnection) url.openConnection(); // 设置请求配置 connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setConnectTimeout(5000); // 连接超时5秒 connection.setReadTimeout(5000); // 读取超时5秒 connection.setDoInput(true); // 3. 获取响应码并处理响应 int responseCode = connection.getResponseCode(); InputStream inputStream = null; if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功,获取正常响应流 inputStream = connection.getInputStream(); } else { // 请求失败,获取错误响应流 inputStream = connection.getErrorStream(); errorMsg = "接口请求失败,响应码:" + responseCode; } // 读取响应数据(兼容各种编码格式) reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } responseJsonStr = sb.toString(); // 若请求失败,直接输出错误信息并终止 if (!errorMsg.isEmpty()) { out.print(errorMsg + ",错误详情:" + responseJsonStr); return; } // 4. 手动解析JSON(避免依赖org.json包,使用字符串截取简化解析,若需完整JSON解析可使用JDK自带的JsonReader) // 简化版:假设接口返回格式固定,直接截取关键参数(若需要更严谨的JSON解析,可参考JDK 11+的javax.json API) // 实际生产环境中,若JDK版本≥11,可使用javax.json(自带,无需额外JAR) String status = ""; String cookieName = ""; String cookieid = ""; long expires = System.currentTimeMillis() + 3600 * 1000; String path = "/"; String domain = ""; boolean secure = false; boolean httponly = true; // 简单截取(仅适用于固定格式的JSON响应,若响应格式复杂,建议使用JDK自带JSON API) if (responseJsonStr.contains("\"status\":\"success\"")) { status = "success"; // 截取cookie_name if (responseJsonStr.contains("\"name\":\"")) { int cookieNameStart = responseJsonStr.indexOf("\"name\":\"") + 14; int cookieNameEnd = responseJsonStr.indexOf("\"", cookieNameStart); cookieName = responseJsonStr.substring(cookieNameStart, cookieNameEnd); } // 截取cookie_id if (responseJsonStr.contains("\"id\":\"")) { int cookieidStart = responseJsonStr.indexOf("\"id\":\"") + 15; int cookieidEnd = responseJsonStr.indexOf("\"", cookieidStart); cookieid = responseJsonStr.substring(cookieidStart, cookieidEnd); } // 截取expires if (responseJsonStr.contains("\"expires\":")) { int expiresStart = responseJsonStr.indexOf("\"expires\":") + 10; int expiresEnd = responseJsonStr.indexOf(",", expiresStart); if (expiresEnd == -1) { expiresEnd = responseJsonStr.indexOf("}", expiresStart); } expires = Long.parseLong(responseJsonStr.substring(expiresStart, expiresEnd).trim()); } // 截取path if (responseJsonStr.contains("\"path\":\"")) { int pathStart = responseJsonStr.indexOf("\"path\":\"") + 8; int pathEnd = responseJsonStr.indexOf("\"", pathStart); path = responseJsonStr.substring(pathStart, pathEnd); } } else { // 截取错误信息 if (responseJsonStr.contains("\"error\":\"")) { int errorStart = responseJsonStr.indexOf("\"error\":\"") + 8; int errorEnd = responseJsonStr.indexOf("\"", errorStart); errorMsg = responseJsonStr.substring(errorStart, errorEnd); } else { errorMsg = "接口返回未知格式数据"; } } // 5. 处理登录跳转逻辑 if ("success".equals(status) && !cookieName.isEmpty() && !cookieid.isEmpty()) { out.print(cookieName+" "+ cookieid); // 关键修正:使用新版Jakarta Servlet API(兼容Tomcat 11) jakarta.servlet.http.Cookie ncCookie = new jakarta.servlet.http.Cookie(cookieName, cookieid); // 计算Cookie有效期(秒为单位) int maxAge = (int) ((expires - System.currentTimeMillis()) / 1000); ncCookie.setMaxAge(maxAge > 0 ? maxAge : 3600); // 至少1小时有效期 ncCookie.setPath(path); // 若有域名需求,设置域名(需与Nextcloud域名一致) if (domain != null && !domain.isEmpty()) { ncCookie.setDomain(domain); } ncCookie.setSecure(secure); // 若使用HTTPS,设置为true ncCookie.setHttpOnly(httponly); // 防止XSS攻击,建议开启 // 发送Cookie到浏览器 response.addCookie(ncCookie); // 跳转Nextcloud主页 //response.sendRedirect("http://192.168.177.116:10081/index.php/apps/files/"); } else { // 登录失败,输出错误信息 out.print("登录失败:" + (errorMsg.isEmpty() ? "未知错误" : errorMsg)); } } catch (Exception e) { // 异常处理 out.print("接口调用异常:" + e.getMessage()); e.printStackTrace(); } finally { // 关闭资源,避免内存泄漏 if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } %> 跳转之后依然是到登录页
12-26
在开发类似视频软件的应用时,需要从功能实现、技术选型参考案例三个方面进行综合考虑。以下是一个基于Objective-C开发的视频软件的技术方案功能实现思路: ### 功能实现 1. **视频采集与播放** 视频采集可以使用AVFoundation框架,它提供了对摄像头麦克风的访问能力。通过`AVCaptureSession`可以配置视频输入源,并将采集到的视频流输出到预览层或进行后续处理。 视频播放则可以使用`AVPlayer`,它支持本地网络视频的播放,并可以自定义播放界面控制逻辑。 2. **视频编码与解码** 视频编码可以使用`VideoToolbox`框架,它提供了硬件加速的编码能力,能够将采集到的原始视频数据(如YUV或RGB)编码为H.264或H.265格式。解码部分同样可以借助`VideoToolbox`完成,将接收到的视频流解码为可渲染的帧数据。 3. **实时视频传输** 实时视频传输可以基于RTP/RTCP协议实现,结合`GCDAsyncUdpSocket`库进行UDP数据包的发送与接收。通过RTP打包视频帧,并在接收端进行解包与播放,确保低延迟的传输效果。 4. **视频特效与滤镜** 视频特效可以通过`Core Image`框架实现,它提供了丰富的滤镜效果,如模糊、锐化、色彩调整等。通过`CIContext`渲染滤镜效果到视频帧上,可以实现实时视频处理。 5. **用户交互与UI设计** 用户交互部分可以使用`UIKit`或`SwiftUI`(如果项目允许混合编程)进行界面设计。例如,视频播放界面可以使用`UIView`或`AVPlayerViewController`,而录制按钮、滤镜切换控件等可以通过自定义`UIButton`或`UISegmentedControl`实现。 ### 技术选型 1. **开发语言与框架** - **Objective-C**:作为主要开发语言,适用于iOS平台的原生开发。 - **AVFoundation**:用于视频采集、播放处理。 - **VideoToolbox**:用于视频编码与解码。 - **Core Image**:用于视频滤镜特效处理。 - **GCDAsyncUdpSocket**:用于实时视频传输。 2. **第三方库与工具** - **FFmpeg**:如果需要更复杂的视频处理功能,可以集成FFmpeg库进行视频转码、格式转换等操作。 - **OpenCV**:如果需要实现高级的视频分析功能(如人脸识别、动作检测),可以使用OpenCV库。 3. **消息传递机制** 在Objective-C中,消息传递机制是核心特性之一。当调用一个方法时,系统会通过`objc_msgSend`函数查找方法的实现(IMP),并执行对应的函数指针。如果找不到方法实现,会进入消息转发机制,包括`resolveClassMethod`、`resolveInstanceMethod`、`forwardingTargetForSelector`、`forwardInvocation`等步骤,最终如果无法处理会抛出异常[^2]。 ### 参考案例 1. **抖音(TikTok)** 抖音的视频采集播放功能非常强大,支持多种滤镜特效。其底层可能使用了类似的框架,如AVFoundationVideoToolbox,并结合自定义的视频处理算法实现高质量的视频效果。 2. **快手** 快手的视频传输模块采用了高效的RTP/RTCP协议栈,结合CDN加速技术,确保了低延迟高并发的视频传输能力。 3. **Zoom** Zoom的视频会议功能涉及多人视频采集、编码、传输解码,其技术方案可以作为多人视频软件开发的参考。 ### 示例代码 以下是一个简单的视频采集与播放的Objective-C代码示例: ```objective-c #import <AVFoundation/AVFoundation.h> @interface ViewController () <AVCaptureVideoDataOutputSampleBufferDelegate> @property (nonatomic, strong) AVCaptureSession *captureSession; @property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self setupCamera]; } - (void)setupCamera { self.captureSession = [[AVCaptureSession alloc] init]; self.captureSession.sessionPreset = AVCaptureSessionPresetHigh; AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; NSError *error = nil; AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error]; if (videoInput) { [self.captureSession addInput:videoInput]; } AVCaptureVideoDataOutput *videoOutput = [[AVCaptureVideoDataOutput alloc] init]; videoOutput.videoSettings = @{ (id)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA) }; [videoOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)]; [self.captureSession addOutput:videoOutput]; self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession]; self.previewLayer.frame = self.view.bounds; [self.view.layer addSublayer:self.previewLayer]; [self.captureSession startRunning]; } - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { // 处理视频帧数据 CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); // 这里可以进行滤镜处理或编码操作 } @end ``` ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值