调用外部短信接口报错
public static String sendSms(String phoneno, String smscontent) {
Map<String, String> param = new HashMap<>();
param.put("PHONENUMBER", phoneno);
param.put("CONTENT", smscontent);
String buildParams = buildParams(param);
log.info("{}-->{}", phoneno, smscontent);
String sendsmsresult = send4GBK("短信接口URL", buildParams);
log.info("短信下发应答:{}", sendsmsresult);
// 错误定位1
Document smdoc = StringTOXml(sendsmsresult);
if (smdoc == null) {
return "error";
}
String returnstatus = getNodeValue(smdoc, "/returnsms/returnstatus");
String message = getNodeValue(smdoc, "/returnsms/message");
if ("Success".equals(returnstatus)) {
return message;
} else {
return message;
}
}
private static Document StringTOXml(String str) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
// 错误定位2
doc = dbf.newDocumentBuilder().parse(is);
is.close();
return doc;
} catch (Exception e) {
// e.printStackTrace();
return null;
}
}
private static String send4GBK(String destURL, String data) {
return sendPost(destURL, data, "GBK");
}
public static String sendPost(String url, String param, String charSet) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestMethod("POST");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
//conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charSet));//"UTF-8"
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
result = "发送 POST请求出现异常,原因:"+ e.getMessage();
System.out.println(result);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
System.out.println(result);
return result;
}
修改过编码和解码的格式,无效;
网上查找错误有说是xml文件格式不正确,但是代码没有xml文件
成功下发短信
StringTOXml 是将字符互传转为xml格式吧,而sendsmsresult的内容不对
你的xml有问题.可能是格式,也可能是编码不一致