我在将数据从Android发送到本地MySQL时遇到问题。 基本信息:
<uses-permission android:name="android.permission.INTERNET"/>
我尝试使用不同的参数设置HttpPost示例:
HttpPost httpPost = new HttpPost("http://10.0.2.2:8080/test.php");
HttpPost httpPost = new HttpPost("http://10.0.2.2/test.php");
HttpPost httpPost = new HttpPost("http://192.168.0.11/test.php");
HttpPost httpPost = new HttpPost("http://127.0.0.1/test.php");
HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/test.php");
HttpPost httpPost = new HttpPost("http://192.168.0.11:8080/test.php");
但它不起作用。
我的Android代码:
public class MainActivity extends Activity {
EditText editTextName;
EditText editTextAge;
EditText editTextEmail;
Button buttonSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.edit_text_name);
editTextAge = (EditText) findViewById(R.id.edit_text_age);
editTextEmail = (EditText) findViewById(R.id.edit_text_email);
buttonSubmit = (Button) findViewById(R.id.button_submit);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
InputStream inputStream = null;
@Override
public void onClick(View v) {
String name = editTextName.getText().toString();
String age = editTextAge.getText().toString();
String email = editTextEmail.getText().toString();
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(1);
nameValuePairList.add(new BasicNameValuePair("name", name));
nameValuePairList.add(new BasicNameValuePair("age", age));
nameValuePairList.add(new BasicNameValuePair("e-mail", email));
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2:8080/test.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
Toast.makeText(getApplicationContext(), "Wyslano", Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e){
Log.d("Log tag", e + "");
}
catch (IOException e){
Log.d("Log tag", e + "");
}
}
});
}
PHP代码:
<?php
$link = mysqli_connect("localhost", "root", "", "android_test_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);
mysqli_free_result($result);
}
$name = isset($_POST['name']);
$age = isset($_POST['age']);
$email = isset($_POST['e-mail']);
mysql_query("insert into login(name, age, e-mail) values ('{$name}','{$age}', '{$email}')");
mysqli_close($link);
?>