【问题标题】:Send POST to a web service and verify some data and send back as JSON将 POST 发送到 Web 服务并验证一些数据并以 JSON 形式发回
【发布时间】:2013-04-27 16:43:31
【问题描述】:

! 我正在开发一个测验应用程序,它使用 PHP Web 服务来创作/托管/维护 Android 测验的数据。

这是有问题的 PHP 函数。

我正在寻找我的 PHP 代码中的帖子。

if (isset($_POST['verifyCourse'])){

verifyCourse($_POST['courseCode']);}

然后 this 指向函数...

function verifyCourse($courseCode){

    $result = mysql_query("SELECT * FROM Course WHERE CourseCode = \"$courseCode\";");
    $rows = array();
    while ($r = mysql_fetch_assoc($result)) {
        $rows = $r;
    }

    if($rows == null){
        return 0;
    } else {
        return json_encode(array('Course' => $rows));
    }

}

然后在我的 Android 代码上,我这样做是为了向名为“verifyCourse”的服务器发送一个 POST,但我没有得到任何回报。

Android:发送 HTTP POSTS 的函数

 public ArrayList<HashMap<String, String>> httpPost(List<NameValuePair> valuepair, String     code)
{
         // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://mydomain.edu/quiz-app/webservice.php");
            StringBuilder builder = new StringBuilder();

            try {

                httppost.setEntity(new UrlEncodedFormEntity(valuepair));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();

                /* Checking response */
                    if (statusCode == 200) {  
                        HttpEntity entity = response.getEntity();
                        InputStream in = entity.getContent(); 

                        Log.d("myapp", "response " + response.getEntity());

                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    String line;
                        while ((line = reader.readLine()) != null) {
                            builder.append(line);
                        } 
                }else{
                    Log.e("POST-return", "Failed to download file");
                }                       

            } catch (Exception e) {
            }
            ArrayList<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();          
            HashMap<String, String> storage =  new HashMap<String, String>(); 
            String value;
            try{
                JSONArray jArray = new JSONArray(builder.toString());
                for(int i=0; i<jArray.length(); i++){
                    JSONObject jsonObject = jArray.getJSONObject(i);
                    value=jsonObject.getString(code);
                    storage = new HashMap<String, String>();
                    storage.put(code, value);
                    results.add(storage);

                }
            } catch (Exception e) {

            }
            return results;



        }

然后我像这样使用它来执行功能。 /// 从应用程序的其他部分传递代码 public void getCourseCodesandVerify(String code) {

    List<NameValuePair> course_info = new ArrayList<NameValuePair>(2);
    course_info.add(new BasicNameValuePair("verifyCourse",null));
    course_info.add(new BasicNameValuePair("courseCode",code));
    httpPost(course_info,null);

}

知道为什么我的代码什么都不返回吗?

这是我返回的 JSON,我该如何处理?

【问题讨论】:

  • 您的 JSON 字符串似乎不在数组中,但它可能只是对象。尝试打印出您的 JSON 并在此处显示
  • 不是答案,但您可能需要考虑将 PDO 用于您的数据库层,因为不推荐使用 mysql_* 函数。现在,如果有人用例如 "1\"; DELETE FROM Course WHERE 1=\"1" 的 courseCode 卷曲你的页面,你可能会大惊小怪。
  • 这是一所大学的项目。我们将在夏天加强它。

标签: java php android json post


【解决方案1】:

mysql_fetch_assoc 返回一个数组。所以在你的代码中你会得到类似的东西:

   echo json_encode(array('Course' => array()));

结果是一个字符串:{"Course":[]}。在 JSON 中,这是一个对象。所以你需要通过以下方式获取它:

JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jArray = jsonObject.getJSONArray("Course");

另请参阅:Reading a Json Array in android

更新

在你的 php 中:

function verifyCourse($courseCode){

   $result = mysql_query("SELECT * FROM Course WHERE CourseCode = \"$courseCode\" LIMIT 1");
   $rows = array();
   while ($r = mysql_fetch_assoc($result))
   {
       $rows[]= $r;
   }   

   header('Content-type: application/json');
   return json_encode(array('Course' => $rows));
   exit;
}

输出如下字符串:

 {"Course":[{"key1":"value1","key2":"value2"},{"2key1":"2value1","2key2":null}]}

在您的 java 代码中:

        JSONObject jsonObject = new JSONObject(builder.toString());



        JSONArray jArray = jsonObject.getJSONArray("Course");



        for(int i = 0; i < jArray.length(); i++){
            JSONObject jObject = jArray.getJSONObject(i);
            Iterator<String> keys = jObject.keys();
            storage =  new HashMap<String, String>();         
            while( keys.hasNext() ){

                   String key = (String)keys.next();
                   storage.put(key, jObject.get(key).toString());

            }

            results.add(storage);
        }

【讨论】:

  • 知道如何为我的代码调整它吗?只需将数组更改为对象?
  • 我的 php 也不能工作吗? return json_encode(array('Course' => $rows));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 2013-11-17
  • 2015-09-12
相关资源
最近更新 更多