调用Geocoding API发起网络请求返回Error 407 (Proxy Authentication Request)错误如何解决?
Google Geocoding API调用407错误排查修复方案
407错误的核心原因是网络代理服务器要求身份认证,请求未携带合法的代理认证信息被拦截,你可以按以下顺序排查遗漏配置:
补全GoogleGeocoder实例化的代理与密钥配置
你当前代码未传入自定义HttpClient配置代理规则,也未传入Google API密钥,是最常见的配置遗漏。参考修复代码:try { // 配置代理处理规则 var proxyHandler = new HttpClientHandler { UseProxy = true, // 使用当前Windows账号的默认凭证做代理认证,大部分企业内网场景适用 UseDefaultCredentials = true, PreAuthenticate = true // 如需手动指定代理地址和账号,替换为如下配置 /* Proxy = new WebProxy("http://代理地址:端口", false) { Credentials = new NetworkCredential("代理用户名", "代理密码", "域(可选)") } */ }; using var httpClient = new HttpClient(proxyHandler); // 第二个参数为你在Google Cloud后台申请的、已启用Geocoding API权限的密钥 IGeocoder geo = new GoogleGeocoder(httpClient, "你的Google API密钥"); Address[] addresses = geo.Geocode(address.Text).ToArray(); foreach (Address adr in addresses) { MessageBox.Show(adr.Coordinates.ToString()); } } catch (Exception ex) { // 先输出完整异常信息确认错误详情 MessageBox.Show(ex.ToString()); // 捕获Web类型的异常获取更详细的响应内容 if (ex is WebException webEx && webEx.Response is HttpWebResponse resp) { using var stream = resp.GetResponseStream(); using var reader = new StreamReader(stream); MessageBox.Show($"响应状态码:{(int)resp.StatusCode}\n响应内容:{reader.ReadToEnd()}"); } }检查项目配置文件的全局代理配置
如果你不想在代码里写死代理配置,可以在项目的app.config(桌面端项目)或web.config(Web项目)中添加全局代理规则:<configuration> <system.net> <defaultProxy enabled="true" useDefaultCredentials="true"> <!-- 不需要自定义代理地址的话可删除下面的proxy节点 --> <proxy proxyaddress="http://你的代理地址:端口" bypassonlocal="True" /> </defaultProxy> </system.net> </configuration>排查网络层面的拦截规则
上述配置都修改后仍报错的话,确认你所在的网络环境是否允许访问Google服务,部分企业内网防火墙会拦截外网API请求,伪装成407错误返回,可以通过浏览器直接调用Geocoding接口测试连通性。
内容的提问来源于stack exchange,提问作者krobelusmeetsyndra
相关产品推荐
相关产品推荐

