简体   繁体   中英

Send POST to a web service and verify some data and send back as JSON

! I am working on a quiz-app that uses a PHP web service to author/host/maintain data for the Android quizes.

Heres is the PHP function in question.

I am looking for a post in my PHP code.

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

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

Any then this points to the function...

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));
    }

}

And then on my Android code I am doing this to send a POST to the server called "verifyCourse" but I am getting nothing in return.

Android: Function to send 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;



        }

I then am using it like this to execute the functionality. /// pass a code from other section of app 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);

}

Any idea why my code just returns nothing...?

Heres what I get back for JSON, how do I process this?

mysql_fetch_assoc returns an array. So in your code you get something like:

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

the result is a string: {"Course":[]} . In JSON this is an object. so you need to fetch it with:

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

See also: Reading a Json Array in android

update

in your 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;
}

Which outputs a string like:

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

in your java code:

        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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM