0

我试过查看几个链接,但我似乎无法正确理解。我正在尝试从我的 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'];

 .....
 ?>

你能告诉我我在这里做错了什么吗?我似乎无法弄清楚。

谢谢

4

1 回答 1

1

NameValuePairs您应该为您的对象添加一个列表HttpPost,这样您就知道可以使用哪些键来检索 PHP 脚本中的数据。请参阅下面的示例代码片段。

爪哇:

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']
于 2013-02-14T23:18:31.043 回答