[英]Sending data to PHP from Android using POST
我無法將數據從我的應用程序發送到本地主機服務器上的PHP腳本。 我可以從PHP腳本中獲取信息,但似乎無法向其發布信息。 我正在嘗試將ID發送到文件中,以用於查詢數據庫。 當我加載PHP文件時,從應用程序發送數據后,我只是得到一個空白頁面,該應用程序在模擬器上運行。 在logcat或加載PHP文件時,我沒有收到任何錯誤。 謝謝你的幫助。
以下是我的完整Java代碼:
public class EventInformation extends Activity
{
private String url = "http://10.0.2.2/Web-Coding/android_get_event.php";
TextView ev_title, ev_desc;
Intent intent;
public String the_title, the_desc;
public HttpClient httpclient;
public HttpPost httppost;
StringBuilder sb1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.eventinformation_layout);
ev_title = (TextView)findViewById(R.id.event_title);
ev_desc = (TextView)findViewById(R.id.event_description);
String text = "Hello!";
new UploadTask().execute(text);
}
private class UploadTask extends AsyncTask<String, Integer, String>
{
private ProgressDialog progressDialog;
@Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(EventInformation.this);
progressDialog.setMessage("Uploading...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
super.onPreExecute();
}
@Override
protected String doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "23"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("TAG", "Response: " + responseStr);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result)
{
if (progressDialog != null) {
progressDialog.dismiss();
}
// process the result
super.onPostExecute(result);
}
}
}
這是獲取和顯示發布的數據的PHP代碼:
<?php
if($_POST)
{
print_r($_POST);
}
?>
在Log.v()之后添加以下行
return responseStr;
這會將響應轉發到onPostExecute()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.