如何为Apache HttpClient的HttpPost请求设置URL参数?
解决Apache HttpClient发送短信时URL参数为空的问题
问题分析
你的代码当前是将SMS对象转成Map后通过map.toString()生成字符串作为POST请求体发送,但存在两个可能导致"参数为空"的问题:
- 如果短信接口要求的是URL查询参数(而非JSON请求体),当前代码完全没有传递URL参数,自然会出现参数为空;
- 如果接口要求JSON请求体,
map.toString()生成的不是标准JSON格式(Java Map的默认输出是{key=value},而非合法的{"key":"value"}),导致后端无法解析参数,表现为参数为空。
解决方案
情况1:接口要求URL查询参数
如果接口需要通过URL传递参数(如http://example.com/sms?phone=13xxxx&content=xxx),使用URIBuilder构建带参数的请求地址:
public void sendSMS(SMS sms) throws IOException, URISyntaxException { String auth = smsUsername + ":" + smsPassword; byte[] encodedAuth = encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); // 构建带查询参数的URI URIBuilder uriBuilder = new URIBuilder(smsEndpoint); ObjectMapper oMapper = new ObjectMapper(); Map<String, Object> paramMap = oMapper.convertValue(sms, Map.class); // 将SMS对象的属性逐个添加为URL查询参数 for (Map.Entry<String, Object> entry : paramMap.entrySet()) { uriBuilder.addParameter(entry.getKey(), entry.getValue().toString()); } HttpPost post = new HttpPost(uriBuilder.build()); post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(encodedAuth)); post.setHeader("Accept", "application/json"); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(post)) { LOGGER.log(Level.INFO, () -> "the response: " + response.toString()); } }
情况2:接口要求JSON请求体
如果接口需要接收JSON格式的请求体,修正JSON字符串的生成方式,避免使用map.toString(),直接用ObjectMapper序列化SMS对象为标准JSON:
public void sendSMS(SMS sms) throws IOException { String auth = smsUsername + ":" + smsPassword; byte[] encodedAuth = encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); ObjectMapper oMapper = new ObjectMapper(); // 直接将SMS对象序列化为标准JSON字符串 String jsonBody = oMapper.writeValueAsString(sms); StringEntity params = new StringEntity(jsonBody, StandardCharsets.UTF_8); HttpPost post = new HttpPost(smsEndpoint); post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(encodedAuth)); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); post.setEntity(params); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(post)) { LOGGER.log(Level.INFO, () -> "the response: " + response.toString()); } }
关键说明
- 先确认短信接口的参数传递规范:是URL查询参数还是JSON请求体,这是解决问题的核心;
- 若使用JSON请求体,必须保证发送的是标准JSON格式,否则后端无法正确解析。
内容的提问来源于stack exchange,提问作者slema imen
相关产品推荐
相关产品推荐

