我试过看几个链接,但我似乎无法做到正确。我试图从我的Android应用程序发送一个包含'用户名'和'密码'的JSON对象。但我不确定这些数据是否实际上已发送到网络服务。我不太确定我是否有正确的代码来读取PHP脚本中的JSON对象。
JSONObject jsonObject = new JSONObject();
String userID = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginURI);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams,10000);
try {
jsonObject.put("username", username);
jsonObject.put("password", password);
JSONArray array = new JSONArray();
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
userID = EntityUtils.toString(httpResponse.getEntity());
Log.i("Read from server", userID);
}
}catch (IOException e){
Log.e("Login_Issue", e.toString());
}catch (JSONException e) {
e.printStackTrace();
}
这是PHP脚本的开头。
<?php
include('dbconnect.php');
$tablename = 'users';
//username and password sent from android
$username=$_REQUEST['username'];
$password=$_REQUEST['password'];
.....
?>
你能告诉我,我在这里做错了吗?我似乎无法弄明白。
谢谢
答案 0 :(得分:1)
您应该在NameValuePairs
对象中添加HttpPost
列表,以便了解可用于在PHP脚本中检索数据的密钥。请参阅下面的示例代码段。
Java:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
PHP:
$username = $_POST['username']
$password = $_POST['password']