通过低端API发送短信

时间:2014-01-09 20:10:20

标签: java multithreading

我有一个表单的消息构造函数方法:

public static String constructMsg(CustomerInfo customer) {
    ... snipped 
    String msg = String.format("Snipped code encapsulated by customer object");

    return msg;
}

API链接是:

http://xxx.xxx.xx.xx:8080/bulksms?username=xxxxxxx& password = xxxx& type = 0& dlr = 1& destination = 10digitno&源= XXXXXX&安培;消息= XXXXX

在我的主要方法中我有:

List<CustomerInfo> customer = dao.getSmsDetails(userDate);

        theLogger.info("Total No : " + customer.size() );

        if (!customer.isEmpty()) {

            for (CustomerInfo cust : customer) {
                String message = constructMsg(cust);

                // Add link and '?' and query string
                // use URLConnection's connect method 
            }
        }

所以我使用了URLConnection的connect方法。 API没有任何文档。有没有办法检查回复?

我的另一个问题是,我被建议使用ThreadPoolExecutor。我如何在这里使用它?

1 个答案:

答案 0 :(得分:1)

此方法使用HTTPURLConnection执行GET请求,将响应作为String返回。有很多方法可以做到这一点,这不是特别精彩,但它真的可读。

public String getResponse(String url, int timeout) {
    HttpURLConnection c;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new              InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
       default:
        return "HTTP CODE: "+status;
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex);
    } finally{
       if(c!=null) c.disconnect();
    }
    return null;
}

像这样调用这个方法:

getResponse("http://xxx.xxx.xx.xx:8080/bulksms?username=xxxxxxx&password=xxxx&type=0 &dlr=1&destination=10digitno&source=xxxxxx&message=xxxxx",2000);

我认为你的URL中的空格不应该在那里。