Java短信注册码与百度api定位(通过http请求实现不需要第三方jar包)

在实际开发过程中大多数情况下注册登录时必不可少的,所以短信验证码的实现用的很多,在这里介绍的后端云平台

Bmob,说句题外话,Bmob对于计算机专业的学生做小的手机应用还是有蛮大帮助的,它能提供一个小型的云数据

库,操作起来也尤为方便,接下来就进入正题吧。
     第一步:注册Bmob帐号

     第二部:身份认证,找不到的话看下图

     

     第三步:阅读官方RESTAPI文档,文档地址:http://docs.bmob.cn/restful/developdoc/index.html?menukey=develop_doc&key=develop_restful#index_短信服务

     文档中的方法是使用http post的方法携带几个必要的参数来通过网络请求使用Bmob后端服务来发送短信,如下图所示:

     其中一个有四个参数,第一个与第二个通过创建应用就可以获得了,第三个是手机号码,第四个是内容,或许有的同学不是太看的懂官方文档,下面我会给出具体的实现代码,想要单纯的使用http方式调试推荐谷歌的插件postman,下面代码使用的访问网络工具是httpclient。

第四步:给出代码

int checkcode = (int)(Math.random()*9000+10000);
Ht
tpClient httpclient = HttpClients.createDefault();
HttpPost httpPost=new HttpPost("https://api.bmob.cn/1/requestSms");
httpPost.addHeader("X-Bmob-Application-Id", "
your appid");
httpPost.addHeader("X-Bmob-REST-API-Key","
your rest id
");
httpPost.addHeader("Content-Type", "application/json");
/
/生成一个附带参数的对象,自己简单的建一个就好

smsObject smo =  new smsObject();
smo.setMobilePhoneNumber(phone);
smo.setContent("your check code is "+checkcode+" , the using time is within 10 minutes");
httpPost.setEntity(new StringEntity(new JSONObject(smo).toString()));
HttpResponse response = httpclient.execute(httpPost);

完工!是不是很简单!不过免费的只有100条,需要更多自己购买。

下面还有一个内容就是百度api 的定位,或许大家平时都使用sdk进行移动应用的开发,但当我只需要简单的位置信息时就会觉得很繁琐,所以百度还提供了通过http请求的方式通过经纬度进行定位。

官方api地址:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

注意看的是逆地理编码服务

我使用的json 的返回类型的http方式,返回的数据会多出一段英文字母与一对小括号,需要自己进行处理一下,传入参数的顺序也要注意,是维度、经度。

别的不多说,直接上代码!

private Location getLocation(String lan,String lng,HttpServletResponse r) throws Exception{
r.setContentType("text/html;charset=utf-8");
Location location = new Location();
String url = "http://api.map.baidu.com/geocoder/v2/?ak=
your api key&callback=renderReverse&location="+lan+","+lng+"&output=json&pois=0";
try {
HttpClient httpclient = HttpClients.createDefault();
HttpGet httpPost=new HttpGet(url);  
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
String content = IOUtils.toString(entity.getContent(),"utf-8");
String aftersubstring1 = content.substring(29);
String aftersubstring2 = aftersubstring1.substring(0, aftersubstring1.length()-1);
System.out.println(aftersubstring2);
JSONObject json = new JSONObject(aftersubstring2);
JSONObject result = json.getJSONObject("result");
JSONObject addresscomponet = result.getJSONObject("addressComponent");
location.setProvince(addresscomponet.getString("province"));
location.setDistrict(addresscomponet.getString("district"));
location.setCity(addresscomponet.getString("city"));
} catch (Exception e) {
// TODO: handle exception
}
return location;

}


     

猜你喜欢

转载自blog.csdn.net/u013407099/article/details/50624560
今日推荐