短信接口要求基于HTTP协议调用,原来只接触过Post、Get请求方式,没有用过Put请求。
1、请求方式PUT---使用到httpclient-4.2.5.jar和httpcore-4.2.4.jar,参考http://download.csdn.net/download/hellosoftware/8744277
请求头的具体含义可以参考:http://tools.jb51.net/table/http_header
public String sendPUT(String restfulUrl, Map<String, String> params) {
HttpClient client = new DefaultHttpClient();
HttpPut requestPut = new HttpPut(restfulUrl);
//设置请求头,根据接口规范做相应调整
requestPut.setHeader("Accept","application/json, application/xml, text/html, text/*, image/*, */*");
final List<BasicNameValuePair> putData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
putData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
if (params != null && !params.isEmpty()) {
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(putData,
HTTP.UTF_8);
requestPut.setEntity(entity);
} catch (UnsupportedEncodingException ignore) {
ignore.printStackTrace();
}
}
String result = "";
try {
HttpResponse httpResponse = client.execute(requestPut);
if (httpResponse == null)
return result;
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
result = EntityUtils.toString(httpResponse.getEntity());
} catch (IOException ignore) {
ignore.printStackTrace();
if (LOG.isErrorEnabled())
LOG.error(ignore);
} finally {
if (client != null)
client.getConnectionManager().shutdown();
}
return result.toString();
}
2、MD5加密 参考:http://blog.csdn.net/miaoyahong/article/details/50561881
public class MD5Util {
public static void main(String[] args) {
String pwd = getMD5("password");
System.out.println(pwd);
}
//生成MD5
public static String getMD5(String message) {
String md5 = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5"); // 创建一个md5算法对象
byte[] messageByte = message.getBytes("UTF-8");
byte[] md5Byte = md.digest(messageByte); // 获得MD5字节数组,16*8=128位
md5 = bytesToHex(md5Byte); // 转换为16进制字符串
} catch (Exception e) {
e.printStackTrace();
}
return md5;
}
// 二进制转十六进制
public static String bytesToHex(byte[] bytes) {
StringBuffer hexStr = new StringBuffer();
int num;
for (int i = 0; i < bytes.length; i++) {
num = bytes[i];
if(num < 0) {
num += 256;
}
if(num < 16){
hexStr.append("0");
}
hexStr.append(Integer.toHexString(num));
}
return hexStr.toString();
}
}