Java 实现发送Http请求
最近需要一个短信业务的接口,发送http请求来发送短信,因为网上给的代码混乱不统一,自己实现了一个,以便自己以后自己使用java发送http请求。
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* Created by yan on 2016/8/5.
*/
public class HttpUtil {
public static void main(String[] args){
HttpUtil httpUtil = new HttpUtil();
httpUtil.SendMessage("http://sms.coocaatv.com/sms/down/",httpUtil.getXmlInfo("13012345678","发送的信息"));
}
public void SendMessage(String url,String xmlFilename){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
postMethod.setRequestBody(xmlFilename);
try {
httpClient.executeMethod(postMethod);
Header[] headers = postMethod.getResponseHeaders();
int statusCode = postMethod.getStatusCode();
System.out.println("code:"+statusCode);
for(Header h : headers){
System.out.println(h.toString());
}
String result = new String(postMethod.getResponseBodyAsString().getBytes("GBK"));
//打印返回的结果
System.out.println(result);
postMethod.releaseConnection();
}catch (Exception e){
e.printStackTrace();
}
}
public String getXmlInfo(String phonenumber,String message) {
StringBuilder sb = new StringBuilder();
//可能每个运营商要求的发送后缀格式不一致,需要自己判断手机号
int state = matchesPhoneNumber(phonenumber);
if(state==2){
message = message+"[]";
}else{
message = message+"【】";
}
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("<data>");
sb.append("</data>");
return sb.toString();
}
public static int matchesPhoneNumber(String phone_number) {
//移动
String cm = "^((13[4-9])|(147)|(15[0-2,7-9])|(18[2-3,7-8]))\\d{8}$";
//联通
String cu = "^((13[0-2])|(145)|(15[5-6])|(186))\\d{8}$";
//电信
String ct = "^((133)|(153)|(18[0,9]))\\d{8}$";
int flag = 0;
if (phone_number.matches(cm)) {
flag = 1;
} else if (phone_number.matches(cu)) {
flag = 2;
} else if (phone_number.matches(ct)) {
flag = 3;
} else {
flag = 4;
}
return flag;
}
}