dragonsun00000 2015-05-15 07:28
浏览 92

使用相同的方法在不同的类中使用不同的HTTP POST?

I am pretty new to Android developement and Java. Currently, I have an application that makes a basic HTTP POST request with a few parameters.

I would like to know if it is possible to make 2 activities that just make the same request but with different parameters, not having to paste the sames methods in the 2 activities.

Example: I have two screens, identics and when I press the button on each screen it sends the post request that I made with different parameters.

PS: What I ask may not be specific enough, so just ask me for details or some code (but I don't think it's necessary here).

Edit : I think I badly explained my thougts :D I have a class with static functions for the post :

public class 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();
}

}

and two activities :

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);
}

}

and

public class OtherClass extends 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.");
    }
}

}

As you see, in the second class, to send different parameters, I must redefine a the functions, and I would like to know if it's the only option (and if it's not bad to do so). Like if I could only in the two class only define the params and make the request.

  • 写回答

4条回答 默认 最新

  • duannai1883 2015-05-15 07:32
    关注

    If I understand you well, you could do this if you create an utils class, where you can paste the methods (public and having parameters that you could pass), that are same for both activities and then call them from the activities like this: UtilsClass.sendPOSTRequest(myparam1, myparam2);

    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序