今天用java 调用 微信分账api 由于上传的数据是xml 格式, 用post请求发送 。在网上找的现成函数,微信服务器老是返回签名错误,但是我用postman 发送返回的数据没有问题,于是经过自己探索,写了个测试可用的post 发送函数,和大家分享一下。
public static String httpPostRequest(String url, String requestStr) throws IOException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(new String(requestStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)));
try (CloseableHttpClient httpclient = httpClientBuilder.build()) {
httpPost.setEntity(new StringEntity(new String(requestStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)));
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
_log.info("\n【请求地址】:{}\n【请求数据】:\n{}\n【响应数据】:\n {}", url, requestStr, responseString);
return responseString;
}
}catch (Exception e){
_log.info("\n【请求地址】:{}\n【请求数据】:\n{}\n【异常信息】:\n{}\n", url, requestStr, e.getMessage());
}
finally {
httpPost.releaseConnection();
}
return null;
}
微信服务器返回的数据如下
<xml>
<return_code><![CDATA[SUCCESS]]></return_code>
<result_code><![CDATA[SUCCESS]]></result_code>
<mch_id><![CDATA[xxxxxxx]]></mch_id>
<appid><![CDATA[xxxxxxxxx]]></appid>
<receiver><![CDATA[{"type":"PERSONAL_WECHATID","account":"xxxx","relation_type":"PARTNER"}]]></receiver>
<nonce_str><![CDATA[bfec794fe03a30b4]]></nonce_str>
<sign><![CDATA[31528954CE0A3CAAE3725AC7BF3CD5F49D604E0DF4F715383F6202B80232D7A0]]></sign>
</xml>