2014-01-09 54 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將這個方法調用包裝在一個循環中嗎? –