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.
我是Android开发和Java的新手。目前,我有一个应用程序,它使用一些参数发出基本的HTTP POST请求。
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.
我想知道是否可以进行2个只发出相同请求但具有不同参数的活动,而不必在2个活动中粘贴相同的方法。
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).
PS:我问的可能不够具体,所以只要问我详细信息或一些代码(但我认为这里没有必要)。
Edit : I think I badly explained my thougts :D I have a class with static functions for the post :
编辑:我想我很清楚地解释了我的想法:D我有一个带有静态函数的类用于帖子:
public class MyHttpPost {
公共类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 {
公共类TestPost扩展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 {
public class 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.");
}
}
}
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.
如你所见,在第二类中,为了发送不同的参数,我必须重新定义函数,我想知道它是否是唯一的选择(如果这样做也不错)。就像我只能在两个班级中定义params并提出请求一样。
4 个解决方案
#1
0
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);
如果我理解你,你可以这样做,如果你创建一个utils类,你可以粘贴方法(公共和你可以传递的参数),这两个活动是相同的,然后从这样的活动中调用它们: UtilsClass.sendPOSTRequest(myparam1,myparam2);
#2
0
You should create a NetworkService
class which contains the method to execute the HTTP POST. The method takes the parameters which are different in your requests. Then create an instance of this class and pass it to both Activities.
您应该创建一个NetworkService类,其中包含执行HTTP POST的方法。该方法采用您的请求中不同的参数。然后创建此类的实例并将其传递给两个活动。
Your new NetworkService
should contain all network-related methods for a better architecture, see Separation of Concerns.
您的新NetworkService应包含所有与网络相关的方法以获得更好的体系结构,请参阅关注点分离。
#3
0
This calls for a NetworkUtils class! This will be a class you should use statically with the same HTTP POST method (the one you want to define in both activities) and call a public static method. Ex:
这需要一个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;
}
}
Check for null in case there is an issue with the network request. Other than that this is just an example of what your solution would look like. (to save extra code!)
如果网络请求出现问题,请检查是否为空。除此之外,这只是您的解决方案的一个示例。 (以节省额外的代码!)
NOTE: This method must be called WITHIN an AsyncThread or a Handler because you are blocking the UI thread when this happens.
注意:必须在AsyncThread或Handler中调用此方法,因为在发生这种情况时您将阻止UI线程。
#4
0
make a global class and define your http method/methods and make them static !! use it from anywhere and pass the parameter as you like
创建一个全局类并定义你的http方法/方法,并使它们保持静态!从任何地方使用它并根据需要传递参数
#1
0
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);
如果我理解你,你可以这样做,如果你创建一个utils类,你可以粘贴方法(公共和你可以传递的参数),这两个活动是相同的,然后从这样的活动中调用它们: UtilsClass.sendPOSTRequest(myparam1,myparam2);
#2
0
You should create a NetworkService
class which contains the method to execute the HTTP POST. The method takes the parameters which are different in your requests. Then create an instance of this class and pass it to both Activities.
您应该创建一个NetworkService类,其中包含执行HTTP POST的方法。该方法采用您的请求中不同的参数。然后创建此类的实例并将其传递给两个活动。
Your new NetworkService
should contain all network-related methods for a better architecture, see Separation of Concerns.
您的新NetworkService应包含所有与网络相关的方法以获得更好的体系结构,请参阅关注点分离。
#3
0
This calls for a NetworkUtils class! This will be a class you should use statically with the same HTTP POST method (the one you want to define in both activities) and call a public static method. Ex:
这需要一个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;
}
}
Check for null in case there is an issue with the network request. Other than that this is just an example of what your solution would look like. (to save extra code!)
如果网络请求出现问题,请检查是否为空。除此之外,这只是您的解决方案的一个示例。 (以节省额外的代码!)
NOTE: This method must be called WITHIN an AsyncThread or a Handler because you are blocking the UI thread when this happens.
注意:必须在AsyncThread或Handler中调用此方法,因为在发生这种情况时您将阻止UI线程。
#4
0
make a global class and define your http method/methods and make them static !! use it from anywhere and pass the parameter as you like
创建一个全局类并定义你的http方法/方法,并使它们保持静态!从任何地方使用它并根据需要传递参数