最近在帮公司使用Java做短信验证的对接业务,网上找到一个使用比较广的短信推送平台螺丝帽(Luosimao.com)该平台提供Java对接开发文档是使用Jersey框架来实现的。按照平台上提供的文档,很容易就对接上了。但是我想到现在Java发送http请求流行使用HttpClient这种更轻量级的专用框架。于是我就试着使用httpClient来实现对接。发现也很容易实现。为了使自己不忘记,在这里记录一下。
maven依赖如下,也可以直接去maven repository下载jar包导入:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Message {
public static void main(String[] args) throws UnsupportedEncodingException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
//填写发送短信的号码
params.add(new BasicNameValuePair("mobile", "155xxxxxxxx"));
//测试默认签名。在平台注册之后可以添加自定义签名,可发送自定义内容
params.add(new BasicNameValuePair("message", "验证码:286221【铁壳测试】"));
HttpEntity reqEntity = new UrlEncodedFormEntity(params, "UTF-8");
sendPost(reqEntity);
}
public static void sendPost(HttpEntity reqEntity) {
//luosimao短信平台短信发送接口URL
HttpPost post = new HttpPost("http://sms-api.luosimao.com/v1/send.json");
//“d609b769db914a4d959bae3414ed1f7X” --APIkey,在luosimao.com注册登陆以后可以得到
post.setHeader("Authorization", "Basic " + Base64.encodeBase64String("api:key-d609b769db914a4d959bae3414ed1f7X".getBytes()));
post.setEntity(reqEntity);
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(post);
HttpEntity respEntity = response.getEntity();
//status code,如200
int statusCode= response.getStatusLine().getStatusCode();
//result,如{"error":0,"msg":"ok"}
String respString = EntityUtils.toString(respEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
post.releaseConnection();
}
}
}