我使用下面的代碼從一個Android應用程序的數據發佈到一個PHP腳本:怪誕當數據發佈到PHP腳本
public class Upload extends Activity implements OnClickListener {
EditText joke;
Button upload = (Button) findViewById(R.id.bUpload);
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
upload.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bUpload:
uploadJoke();
break;
}
}
private void uploadJoke() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxx/telejoke.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "test"));
nameValuePairs.add(new BasicNameValuePair("joke", joke.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
此代碼將數據發送到PHP腳本,然後將它發送到一個SQL數據庫。這些數據顯示在SQL數據庫中,但是如果我嘗試類似echo $username
的內容,那麼當我轉到http://xxxx/telejoke.php時,它不會顯示用戶名。
PHP腳本:
<?php
include 'DBConnect.php';
include 'JokeValidate.php';
$username = $_POST['username'];
$joke = $_POST['joke'];
$dbname = 'Telejoke';
mysql_select_db($dbname);
echo $username. " " . $joke;
if (validate()){
$query = "INSERT INTO jokes (username, joke) VALUES ('$username','$joke')";
mysql_query($query) or die('Error, insert query failed');
}
mysql_close($conn);
?>
請幫助。除了將它發送到數據庫之外,我想用PHP來發布數據。
如果數據使它到數據庫好,那麼我們需要看telejoke.php,因爲沒有什麼錯java代碼。 – drew010 2012-04-09 17:53:17
爲什麼不發佈你的php代碼?這個客戶端代碼不會幫你處理服務器代碼中的問題 – EMI 2012-04-09 17:54:21
按鈕點擊是definitley工作。上傳後,我可以在數據庫中看到數據。 EditText笑話用於'nameValuePairs.add(new BasicNameValuePair(「joke」,joke.getText()。toString())); ' – moesef 2012-04-09 18:28:20