我正在尝试从一个 android 应用程序到一个将更新数据库的 php 脚本做一个非常简单的 POST。不幸的是,这在第 52 行给了我一个调试器错误(eclipse)。下面是代码:
package com.example.testhttppost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void updateDiscountTable(View view)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.test.com/jsonpost.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("shop", "ZARA"));
nameValuePairs.add(new BasicNameValuePair("discount", "20%"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost); //Line 52
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
PHP脚本是:
<?php
// PHP variable to store the host address
$db_host = "localhost";
// PHP variable to store the username
$db_uid = "dsdsdsv_android";
// PHP variable to store the password
$db_pass = "test1234";
// PHP variable to store the Database name
$db_name = "dsdsdsv_android";
// PHP variable to store the result of the PHP function 'mysql_connect()' which establishes the PHP & MySQL connection
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$shopId = $_POST['id'];
$shopName = $_POST['shop'];
$discount = $_POST['discount'];
mysql_query("insert into discounts(id, shop, discount) values ($shopId, $shopName, $discount)");
// mysql_query("insert into discounts(id, shop, discount)values(121, 'sadsdas','dasdasdsa')");
?>
应用程序的界面只是一个按钮。此按钮与上面定义的 updateDiscountTable 方法链接。感谢并期待回复。