我有一个问题想解决一整天。也许你们其中一个 知道我哪里出了问题吗?
我正在尝试让Android Activity通过PHP将值发布到MySQL DB中。 当我将PHP脚本与服务器同一目录中的HTML文件一起使用时,它可以正常工作。因此,我很确定,Android文件存在问题。但是:Android文件到达php文件,并在数据库中创建一个条目。但是该值始终为空。
我有这样的Android活动:
public class MainActivity extends AppCompatActivity {
public static final MediaType MEDIA_TYPE =
MediaType.parse("application/json");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final OkHttpClient client = new OkHttpClient();
JSONObject postdata = new JSONObject();
try {
postdata.put("Mail", "Tim");
postdata.put("Password", "44");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestBody body = RequestBody.create(MEDIA_TYPE,
postdata.toString());
final Request request = new Request.Builder()
.url("MYURL")
.post(body)
.addHeader("Content-Type", "application/json") //
.addHeader("Authorization", "Your Token") //
.addHeader("cache-control", "no-cache")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
String mMessage = e.getMessage().toString();
Log.w("failure Response", mMessage);
//call.cancel();
}
@Override
public void onResponse(Call call, Response response)
throws IOException {
String mMessage = response.body().string();
if (response.isSuccessful()) {
try {
JSONObject json = new JSONObject(mMessage);
final String serverResponse = json.getString("Your Index");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
}
像这样的PhP文件:
<?php
echo 'PHP-File works<br>';
$link = mysqli_connect("MYHOSTNAME", "USERNAME", "PASSWORD",
"DBNAME");
if (!$link) {
echo 'Link doesnt work';
}
if (mysqli_connect_errno()) {
echo 'Connection Error';
}
$Mail = mysqli_real_escape_string($link, trim($_POST['Mail']));
$Password = mysqli_real_escape_string($link, trim($_POST['Password']));
if(!mysqli_query($link, 'INSERT INTO Volley_Sample_2 (email, password)
VALUES ("hardcode_test",4)')){
echo ("Error description: " . mysqli_error($link));
}
$query = "INSERT INTO Volley_Sample_2 (email, password) VALUES('$Mail',
'$Password')";
mysqli_query($link,$query) or trigger_error(mysqli_error($link)." in
".$query);
mysqli_close($link);