URL路径中包含中文,使用httpsurlconnection无法连接

本文介绍了解决URL路径中中文字符导致的httpsurlconnection连接失败问题的方法。关键在于正确使用URLEncoder对URL路径中的中文部分进行编码,避免对整条URL进行编码而引起错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

URL路径中包含中文,使用httpsurlconnection无法连接

需要对中文进行编码,需要注意的一点是不能对整条url进行编码,因为这样会将路径中的“/”也被编码,导致报错java.net.MalformedURLException: no protocol。
下面这个方法适合路径中本身包含中文,如果参数中有中文,需要对参数进行编码。

URL url1 = new URL(url.substring(0, url.lastIndexOf("/"))
                   + URLEncoder.encode(url.substring(url.lastIndexOf("/")+1, url.length()), "utf-8")); 
private String httpsdeviceRegister() { try { // 1. 创建URL对象 //URL url = new URL("https://your-api-endpoint.com/post"); // 2. 打开HTTPS连接 HttpsURLConnection conn = (HttpsURLConnection) deviceRegisterUrl.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); // 3. 设置请求头 conn.setRequestProperty("Content-Type", "application/json; utf-8"); conn.setRequestProperty("Accept", "application/json"); // 4. 构建请求体 String jsonInputString = "{\"deviceId\": \"123456789012340\", \"deviceType\": \"huawei mate40\", \"readerMac\": \"2435567840\", \"sdkVersion\": \"100\"}"; //debug setting // 在conn.getOutputStream()之前添加: SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{ new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) {} public void checkServerTrusted(X509Certificate[] chain, String authType) {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new SecureRandom()); conn.setSSLSocketFactory(sslContext.getSocketFactory()); conn.setHostnameVerifier((hostname, session) -> true); // 关闭主机名验证 //debug setting end // 5. 发送请求数据 try(OutputStream os = conn.getOutputStream()) { byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } // 6. 获取响应 int code = conn.getResponseCode(); if (code == HttpsURLConnection.HTTP_OK) { try(BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } return response.toString(); } } return "HTTP Error: " + code; } catch (Exception e) { Log.e(TAG, "Request failed", e); return "Error: " + e.getMessage(); } }HTTP Error: 405
04-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值