【发布时间】:2017-03-17 18:29:48
【问题描述】:
我正在开发一个需要同时更新 2 个 PHP 数据库的应用程序。从第一个 PHP 数据库中,我得到了需要在主屏幕上显示的数据,因此它在 onPostExecute 中处理。但是对于第二个 PHP 数据库,我需要检查和更新其中的记录,我无法弄清楚如何在一个 Java 程序中执行多个 PHP 请求。代码如下:
Java 代码
public class BackgroundTask extends AsyncTask<String, Void, String> {
String json_url;
Context context;
public BackgroundTask (Context c) { context = c;}
public BackgroundTask() {
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "... my link ..."; // to get data of the user
if (type.equals("login")) {
try {
String user_name = params[1];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
StringBuilder stringBuilder = new StringBuilder();
String results = "";
String line = "";
while ((STRING_JSON = bufferedReader.readLine()) != null) {
results += line;
stringBuilder.append(STRING_JSON + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
//connectionStatus = true;
Log.i("doInBackgroundTry->try", "stringbuilder in the end is " + stringBuilder.toString());
master_string = stringBuilder.toString().trim();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
Toast.makeText(context, "malformed exception error is " + e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
public void onPreExecute() {
json_url = " ... my link ...";
}
@Override
public void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
public void onPostExecute(String result) {
// random updation of the UI
}
}
所有第二个 PHP 数据库都有一个 ID,将检查它是否已经在表中,如果是,则不会发生任何事情,但如果不是,则将其添加到数据库中。
【问题讨论】:
-
您可以尝试更改您的类型变量。就像当您调用执行时,您必须告诉它您使用 php 代码的方法类型,您可以通过添加另一个 else if 来更改您的 if ( type.equals("login") ),如下所示: else if ( type.equals ("second_query") ) ...
-
你能再详细点吗?
-
我会发布一个答案,我很确定我的方法是正确的......等待一段时间......