请帮忙。 我想使用okhttpclient将数据从android插入服务器(php),代码不起作用。 请帮助,我已经花了更多的时间停留在那个
谢谢。
这是我的PHP代码:
$con=mysqli_connect("localhost","root","","Androidtesting");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['email']))
{
//insert query
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "INSERT INTO users (email, password)
VALUES (".$email.", ".$password.");";
mysqli_query($con, $sql);
}
mysqli_close($con);
我的安卓代码:
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
String email = "myemail";
String password = "mypassword";
RequestBody body = new FormEncodingBuilder()
.add("contentType", "application/x-www-form-urlencoded")
.add("email", email)
.add("password", password)
.build();
Request request = new Request.Builder()
.url("http://10.0.2.2/AndroidTestingProject/data.php")
.post(body)
.build();
Response response = client.newCall(request).execute();
response.body().string();
if (!response.isSuccessful()) throw new
IOException("Unexpected code " + response);
}catch(Exception e)
{
System.out.println("FIL FUNCTION errroros hwa "+e);
}
}
});
thread.start();
答案 0 :(得分:0)
最后我在php代码中找到了答案..它应该如下所示。
foreach ($_POST as $key => $value) {
switch ($key) {
case 'email':
{
echo $firstKey = $value;
}
break;
case 'password':
echo $secondKey = $value;
break;
default:
break;
}
}