【问题标题】:Can't access the sms gateway from spring resttemplate无法从 spring resttemplate 访问短信网关
【发布时间】:2017-08-24 08:46:19
【问题描述】:

我有短信网关,我可以提供网址并发送短信,如下所示。

"https://url/destination={mobileNum}&q=mypw\n&message={msg}\n"

我在 resttemplate 中使用过它并尝试发送短信,但它没有用。

public String send(String mobileNumber, String message) {

    String uri = "https://url/destination={mobileNum}&q=mypw\n&message={msg}\n";
    RestTemplate restTemplate = new RestTemplate();

    URI result = restTemplate.postForLocation(uri, mobileNumber, message);


    return result.toString();
    //return null;
}

代码的其他部分工作正常。它没有给出任何错误。但短信发送部分不起作用。我该如何解决这个问题?

【问题讨论】:

  • 也显示响应部分..您从短信网关 web 服务收到的内容

标签: java spring rest resttemplate


【解决方案1】:

我猜你在 URL 中使用的 new-line 字符有问题。尝试逃跑\

使用 queryParams 时 URL 的另一个问题。查询参数应该在? 分隔符之后。

所以最终到达网址可能如下所示:

String uri = "https://url?destination={mobileNum}&q=mypw\\n&message={msg}\\n";

The components of a URL

【讨论】:

  • @SanduniWickramasinghe 如果没有服务器的响应和 SMS 网关的规范,很难说更多,但尝试在 postForEntity 上更改 postForLocation 并输出响应。
  • 当我在浏览器搜索栏中输入短信网关时,它工作正常,短信发送到我的手机
  • 当更改为 postForEntity 参数变得不兼容
  • 网址没有问题。我只想知道代码中的错误
  • 能否请您显示来自服务器的响应?没有上下文很难说更多
【解决方案2】:

试试这个。

public String send(String mobileNumber, String message) {

String uri = "https://url/destination=" mobileNumber + "&q=mypw&message="+message;
RestTemplate restTemplate = new RestTemplate();

String result = restTemplate.getForObject(uri, String.class);
return result;

}

根据 RestTemplate 文档,方法 postForLocation 用于通过将给定对象发布到 URI 模板来创建新资源,并返回 Location 标头的值。此标头通常指示新资源的存储位置。 RestTemplate docs

服务器可能不允许查询新资源的位置,因此不会发送位置标头作为响应。

【讨论】:

  • 这个方法怎么给手机号和短信?。没有手机号码无法发送短信
  • 如果它在 url 中,则通过添加 mobileNumber 和消息来构造 url
  • 它会不时变化。取自用户
【解决方案3】:

读取 URL 时出错。 “mypw&message”被用作密码,而不仅仅是“mypw”。我是在使用jboss调试模式调试代码时发现的。

这是最终代码

@Service
public class SmsServiceImpl implements SmsService{

@Override
public String send(String mobileNumber, String message) {
    String uri = "https://urlTodestination="+mobileNumber+"&q=pw&message="+message;

    RestTemplate restTemplate = new RestTemplate();

    String result = restTemplate.getForObject(uri,  String.class);

    return result;
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    相关资源
    最近更新 更多