Java 实现发送Http请求

5 篇文章 0 订阅

最近需要一个短信业务的接口,发送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;

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值