使用模拟器时SSL连接无法建立的技术问题求助
问题:Android模拟器调用IIS Web API时SSL连接失败
我有两个Visual Studio项目:一个是运行IIS的Web应用,另一个是在模拟器调试模式下运行的C# Android项目。使用HttpClient向Web应用的API发送请求时,出现错误:
The SSL connection could not be established, see inner exception.
此前曾遇到错误:
Javax.Net.Ssl.SSLHandshakeException: 'java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.'
已在MainActivity.cs中添加代码尝试绕过证书校验,但问题仍未解决:
ServicePointManager.ServerCertificateValidationCallback += (o, cert, chain, errors) => true;
目前可通过浏览器使用与Android应用相同的URL正常访问该API,寻求技术解决方案。
客户端代码
PhotoImage.Source = ImageSource.FromFile(PhotoPath); byte[] imageBytes = File.ReadAllBytes(PhotoPath); var base64image = System.Convert.ToBase64String(imageBytes); // Create an HTTP web request using the URL: var jn = JobNo.Text.ToString(); var url = serverurl + "api/Data/uploadimage"; var httpClient = new HttpClient(new System.Net.Http.HttpClientHandler()); var form = new MultipartFormDataContent(); form.Add(new ByteArrayContent(imageBytes, 0, imageBytes.Length), "base64image", "hello1.jpg"); var response = await httpClient.PutAsync(url, form); response.EnsureSuccessStatusCode();
服务端API代码
// PUT api/<DataController>/uploadimage [HttpPut] [Route("uploadimage/")] public void uploadimage(string base64image) { try { var stream = Request.BodyReader.AsStream(); byte[] buffer = new byte[Request.Body.Length]; //stream.Write(buffer); } catch (System.Exception) { throw; } }
解决方案
1. 替换证书校验方式(适配Android平台)
ServicePointManager是.NET Framework专属API,在Xamarin/MAUI Android环境下不生效,需给HttpClientHandler直接配置证书校验回调:
var handler = new HttpClientHandler(); // 全局绕过证书校验(仅调试环境使用) handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; var httpClient = new HttpClient(handler);
2. 修复IIS证书与访问地址问题
- 避免使用localhost:模拟器的
localhost指向自身,需改用电脑的局域网IP或自定义主机名(如https://192.168.x.x/api/Data/uploadimage) - 安装自签名证书到模拟器:如果IIS使用自签名证书,需将证书导出为
.cer格式,拖入模拟器后,通过「设置-安全-加密与凭据-从存储安装」将证书添加到系统信任区
3. 修正客户端与服务端的参数匹配问题
客户端用MultipartFormDataContent上传文件流,但服务端接收参数为string base64image,参数格式不匹配会导致请求解析失败,二选一修改:
- 客户端修改为传base64字符串:
var content = new StringContent(base64image, Encoding.UTF8, "application/json"); var response = await httpClient.PutAsync(url, content); - 服务端修改为接收表单文件:
[HttpPut] [Route("uploadimage/")] public async Task UploadImage() { var formFile = Request.Form.Files["base64image"]; if (formFile != null) { using (var stream = new MemoryStream()) { await formFile.CopyToAsync(stream); var imageBytes = stream.ToArray(); // 处理图片字节逻辑 } } }
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

