2016-02-23 59 views
-1

我需要幫助將此代碼從Java轉換爲Android Studio Java。這是一個短信網關代碼,試圖在我的Android應用程序中使用它發送短信給用戶。如何將此SMS網關Java代碼轉換爲Android Studio代碼

private static String doHttpPost(String urlString, String requestString) { 
    try { 
     URL url = new URL(urlString); 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 

     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     wr.write(requestString); 
     wr.flush(); 
     // Get the response 
     BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     String line; 
     String response = ""; 
     while ((line = rd.readLine()) != null) { 
      response += line; 
     } 
     wr.close(); 
     rd.close(); 

     return response; 
    } catch (IOException ex) { 
     System.err.println(ex); return ex.toString(); 
    } 
} 
+0

什麼短信網關的代碼?它應該工作,只要它包裝在一個AsyncTask中。 – Helix

+0

@Helix我正在使用cm電信,我如何用AsyncTask包裝它 – henry

+0

我正在通過URL獲得一條紅線@Helix – henry

回答

0

您使用的請嘗試以下代碼

public class PostAsyncTask extends AsyncTask<Void, Void, String>{ 

    String requestString; 
    String urlString; 

    public PostAsyncTask(String urlString, String requestString){ 
     this.urlString = urlString; 
     this.requestString = requestString; 
    } 


    @Override 
    String doInBackground(Void... void){ 

    try { 
     URL url = new URL(urlString); 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 

     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     wr.write(requestString); 
     wr.flush(); 
     // Get the response 
     BufferedReader rd = new BufferedReader(new InputStreamReade(conn.getInputStream())); 
     String line; 
     String response = ""; 
     while ((line = rd.readLine()) != null) { 
      response += line; 
     } 
     wr.close(); 
     rd.close(); 

     return response; 
    } catch (IOException ex) { 
     System.err.println(ex); return ex.toString(); 
    } 

    } 

    @Override 
    onPostExecute(String result){ 

     //Code to handle result here 

    } 



} 

調用此使用

new PostAsyncTask(urlString, requestString).execute(); 
+0

這個答案真的有幫助,非常感謝@Helix – henry