2014-01-09 53 views
0

我有形式的消息构造方法:发送SMS

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 &密码= XXXX &类型= 0 & DLR = 1 &目的地= 10digitno & source = xxxxxx & message = xxxxx

在我的主要方法中,我有:(s):

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。我会如何在这里使用它?

+0

这没有任何意义。 'constructMsg('需要一个它不使用的参数。为什么? – acdcjunior

+0

已编辑的代码我只添加了重要的位 –

回答

1

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

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中的空格不应该在那里。

+0

感谢您的回答。为什么200代码条件留空?您能否扩展201代码?我觉得线程是不需要的 –

+1

200和201由同一个案件处理201通过一些后端API成功返回,所以我将它包含在答案中 – elbuild

+0

哦,我怎么能错过那个开关语义!谢谢。 Btw将这个方法调用包装在一个循环中吗? –