Java中使用Apache Commons HttpClient发送POST请求时如何编码[]并解决非法字符错误
解决Apache Commons HttpClient中POST请求URL包含[]字符的非法字符错误
这个问题我之前踩过坑!你遇到的非法字符错误,根源是直接把包含[和]的JSON字符串硬拼进了URL查询参数里——这两个字符属于URL的保留字符,直接使用会违反URL规范,触发非法字符校验失败。
推荐解决方案:用URIBuilder自动处理参数编码
Apache HttpClient提供了URIBuilder工具类,能帮你自动完成所有参数的URL编码,包括[、]这类特殊字符,完全不用手动处理。调整后的代码如下:
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.net.URI; import java.net.URISyntaxException; public class PaymentSplitExample { public static void main(String[] args) throws URISyntaxException { // 1. 初始化URIBuilder,只传入基础URL(不带参数) URIBuilder uriBuilder = new URIBuilder("https://www.payumoney.com/payment/payment/addPaymentSplit"); // 2. 逐个添加参数,普通参数直接传值即可 uriBuilder.addParameter("merchantKey", "test"); uriBuilder.addParameter("merchantTransactionId", "test"); uriBuilder.addParameter("totalAmount", "0"); uriBuilder.addParameter("totalDiscount", "0"); // 3. 添加包含[]的JSON参数,URIBuilder会自动编码特殊字符 String jsonSplits = "[{\"amountToBeSettled\":0,\"aggregatorDiscount\":0,\"splitDetails\":\"test\",\"CODAmount\":0,\"splitAmount\":0,\"merchantId\":\"0000\",\"aggregatorCharges\":0,\"CODMode\":0,\"aggregatorSubTransactionId\":\"test\",\"sellerDiscount\":0}]"; uriBuilder.addParameter("jsonSplits", jsonSplits); // 4. 构建合法的URI,再创建HttpPost请求 URI validUri = uriBuilder.build(); HttpPost post = new HttpPost(validUri); // 后续发送请求的逻辑不变 try (CloseableHttpClient client = HttpClients.createDefault()) { client.execute(post); // ...处理响应 } catch (Exception e) { e.printStackTrace(); } } }
URIBuilder会按照RFC 3986规范自动把[转换成%5B,]转换成%5D,生成的URL完全符合规范,不会触发非法字符错误。
备选方案:手动编码单个参数值(不推荐)
如果你坚持要手动拼接URL,可以用URLEncoder.encode()方法单独对包含特殊字符的参数值进行编码,注意只编码参数值,不要编码整个URL:
import java.net.URLEncoder; import java.nio.charset.StandardCharsets; // ... String jsonSplits = "[{\"amountToBeSettled\":0,...}]"; // 对JSON参数值单独编码 String encodedJsonSplits = URLEncoder.encode(jsonSplits, StandardCharsets.UTF_8.name()); // 拼接URL时使用编码后的参数值 String url = "https://www.payumoney.com/payment/payment/addPaymentSplit?merchantKey=test&merchantTransactionId=test&totalAmount=0&totalDiscount=0&jsonSplits=" + encodedJsonSplits; HttpPost post = new HttpPost(url);
这种方式容易出错(比如忘记编码其他特殊字符),所以还是优先用URIBuilder更稳妥。
内容的提问来源于stack exchange,提问作者Explain Down Vote
相关产品推荐
相关产品推荐

