我想要一个简单的代码将我的android应用程序中的字符串变量发布到我的php脚本。
php代码:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "table";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name=$_POST["name"];
$sql = "INSERT INTO t (name)
VALUES ('$name')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
我想要一个代码将我的字符串发送到php并与php代码兼容, 我确信php工作正常。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText text = (EditText) findViewById(R.id.x);
Button btn = (Button) findViewById(R.id.b);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String name = text.getText().toString();
}
});
}
}
答案 0 :(得分:1)
您可以使用下面的Android Volley Post Method
String url = "PATH_TO YOUR_SERVER";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>(){
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
@Override
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("NAME", name);
return params;
}
};
queue.add(postRequest);