2015-05-15 45 views
1

我对Android开发和Java非常新颖。目前,我有一个应用程序使用一些参数进行基本的HTTP POST请求。不同的HTTP POST在不同的类中使用相同的方法?

我想知道是否可以做2个活动,只是提出相同的请求,但具有不同的参数,不必粘贴相同的方法在2活动

例如:我有两个屏幕,标识,当我按下每个屏幕上的按钮时,它会发送我用不同参数创建的发布请求。 PS:我所要求的可能不够具体,所以只要问我一些细节或代码(但我不认为这是必要的)。

编辑:我觉得我不好解释了我的thougts:d 我与该职位的静态函数的类:

公共类MyHttpPost {

public static String performPostCall(String requestURL, HashMap<String, String> postDataParams) throws IOException { 

    InputStream is = null; 
    int len = 500; 
    URL url; 

    try { 
     url = new URL(requestURL); 

     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(15000); 
     conn.setConnectTimeout(15000); 
     conn.setRequestMethod("POST"); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 

     OutputStream os = conn.getOutputStream(); 

     BufferedWriter writer = new BufferedWriter(
       new OutputStreamWriter(os, "UTF-8")); 
     writer.write(getPostDataString(postDataParams)); 

     writer.flush(); 
     writer.close(); 
     os.close(); 

     is = conn.getInputStream(); 

     return readIt(is, len); 

    } finally { 
     if (is != null) { 
      is.close(); 
     } 
    } 
} 

public static String readIt(InputStream stream, int len) throws IOException { 
    Reader reader = new InputStreamReader(stream, "UTF-8"); 
    char[] buffer = new char[len]; 
    reader.read(buffer); 
    return new String(buffer); 
} 

private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { 
    StringBuilder result = new StringBuilder(); 
    boolean first = true; 
    for(Map.Entry<String, String> entry : params.entrySet()) { 

     if (first) 
      first = false; 
     else 
      result.append("&"); 

     result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); 
     result.append("="); 
     result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); 
    } 

    return result.toString(); 
} 

}

和两个活动:

public class TestPost extends AppCompatActivity {

public final static String EXTRA_MESSAGE = "MESSAGE"; 

private TextView myView; 
private EditText urlText; 
HashMap<String, String> postDataParams; 
WebView webview; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_test_post); 

    myView = (TextView)findViewById(R.id.myText); 
    urlText = (EditText)findViewById(R.id.myUrl); 

    postDataParams = new HashMap<>(); 
    postDataParams.put("firstParam", "1234"); 
    postDataParams.put("secondParam", "qwerty"); 

    webview = new WebView(this); 
    webview = (WebView) findViewById(R.id.myWebView); 

} 

public void sendMessage(View view) { 
    Intent intent = new Intent(this, Home.class); 

    TextView editTextview = (TextView) findViewById(R.id.myText); 
    String message = editTextview.getText().toString(); 
    intent.putExtra(EXTRA_MESSAGE, message); 
    startActivity(intent); 
} 

protected class DownloadWebpageTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... urls) { 

     // params comes from the execute() call: params[0] is the url. 
     try { 
      return MyHttpPost.performPostCall(urls[0], postDataParams); 
     } catch (IOException e) { 
      return getResources().getString(R.string.bad_url); 
     } 
    } 
    // onPostExecute displays the results of the AsyncTask. 
    @Override 
    protected void onPostExecute(String result) { 
     myView.setText(result); 
     webview.loadData(result, "text/html", null); 
    } 
} 

// When user clicks button, calls AsyncTask. 
// Before attempting to fetch the URL, makes sure that there is a network connection. 
public void myClickHandler(View view) { 
    // Gets the URL from the UI's text field. 
    String stringUrl = urlText.getText().toString(); 
    ConnectivityManager connMgr = (ConnectivityManager) 
      getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     new DownloadWebpageTask().execute(stringUrl); 
    } else { 
     myView.setText("No network connection available."); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_test_post, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

}

公共类OtherClass扩展TestPost {

private TextView myView; 
private EditText urlText; 
HashMap<String, String> postDataParams; 
WebView webview; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_test_post); 

    myView = (TextView)findViewById(R.id.myText); 
    urlText = (EditText)findViewById(R.id.myUrl); 
    myView.setText("coucou"); 

    postDataParams = new HashMap<>(); 
    postDataParams.put("firstParam", "9876"); 
    postDataParams.put("secondParam", "ytreza"); 

    webview = new WebView(this); 
    webview = (WebView) findViewById(R.id.myWebView); 
} 

protected class DownloadWebpageTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... urls) { 

     // params comes from the execute() call: params[0] is the url. 
     try { 
      return MyHttpPost.performPostCall(urls[0], postDataParams); 
     } catch (IOException e) { 
      return getResources().getString(R.string.bad_url); 
     } 
    } 
    // onPostExecute displays the results of the AsyncTask. 
    @Override 
    protected void onPostExecute(String result) { 
     myView.setText(result); 
     webview.loadData(result, "text/html", null); 
    } 
} 

public void myClickHandler(View view) { 
    // Gets the URL from the UI's text field. 
    String stringUrl = urlText.getText().toString(); 
    ConnectivityManager connMgr = (ConnectivityManager) 
      getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     new DownloadWebpageTask().execute(stringUrl); 
    } else { 
     myView.setText("No network connection available."); 
    } 
} 

}

正如你看到的,在第二类中,发送不同的参数,我必须重新定义一个函数,我想知道它是否是唯一的选择(如果这样做不坏)。 如果我只能在这两个类中定义参数并提出请求。

+0

Ofcourse你可以用不同的参数运行一个单一的方法,这就是OOP的目的。 – Skynet

+0

您可以在不同的类(如util)中定义方法(在该调用http post中)并使用不同的参数从不同的活动中调用该方法 –

回答

0

如果我很了解你,如果你创建了一个utils类,你可以粘贴方法(public和有可以传递的参数),这两个activity都是相同的,然后从像这样的活动:UtilsClass.sendPOSTRequest(myparam1, myparam2);

0

您应该创建一个NetworkService类,其中包含执行HTTP POST的方法。该方法使用您的请求中不同的参数。然后创建该类的一个实例并将其传递给两个活动。

您的新NetworkService应包含所有与网络有关的方法以获得更好的体系结构,请参阅Separation of Concerns

0

这需要一个NetworkUtils类!这将是一个类,您应该使用相同的HTTP POST方法(您想在两个活动中定义的方法)静态使用并调用公共静态方法。例如:

public class NetworkUtils{ 

    public static HttpResponse postData(String param1, String param2) { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

     try { 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("id", param1)); 
      nameValuePairs.add(new BasicNameValuePair("stringdata", param2)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // Execute HTTP Post Request, return response 
      return httpclient.execute(httppost); 

     } catch (ClientProtocolException e) { 
      e.printStacktrace(); 
     }catch (IOException e) { 
      e.printStacktrace(); 
     } 
     return null; 
    }  
} 

如果网络请求存在问题,请检查为空。除此之外,这只是您的解决方案的一个例子。 (以节省额外的代码!)

注意:此方法必须在AsyncThread或处理程序中调用,因为您在这种情况发生时阻止UI线程。

+0

HttpPost在api 22中不推荐使用。您应该使用'HttpUrlConnection'代替。 http://developer.android.com/reference/org/apache/http/client/methods/HttpPost.html – Raghunandan

+0

不够公平。他的问题是如何处理最小化代码复制问题,所以我的例子只是演示如何在utils类中使用您首选的HTTP库。 –

+0

这就是为什么发布此作为评论,以防有人需要信息 – Raghunandan

0

创建一个全局类并定义你的http方法并使它们成为静态的!在任何地方使用它,只要你喜欢传递参数

相关问题