IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Android Discussion :

[Web Service] Problème requête HttpClient


Sujet :

API standards et tierces Android

Mode arborescent

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Par défaut [Web Service] Problème requête HttpClient
    salut
    en suivant un tutoriel sur le web service avec android (php et mysql). j'ai fais face à un problème: j'arrive à afficher la liste des produits ainsi qu'ajouter des produits (càd l'accès au serveur de base de données s'effectue avec succès) cependant lorsque je veux consulter les détails d'un produits j'ai une erreur dans LogCat que je ne comprends pas.
    voilà le code .java de la classe qui affiche les détails:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    public class EditProductActivity extends Activity {
     
        EditText txtName;
        EditText txtPrice;
        EditText txtDesc;
        EditText txtCreatedAt;
        Button btnSave;
        Button btnDelete;
     
        String pid;
     
        // Progress Dialog
        private ProgressDialog pDialog;
     
        // JSON parser class
        JSONParser jsonParser = new JSONParser();
     
        // single product url
        private static final String url_product_details = "http://monsite.com/get_product_details.php";
     
        // url to update product
        private static final String url_update_product = "http://android.com/update_product.php";
     
        // url to delete product
        private static final String url_delete_product = "http://android.com/delete_product.php";
     
        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_PRODUCT = "product";
        private static final String TAG_PID = "pid";
        private static final String TAG_NAME = "name";
        private static final String TAG_PRICE = "price";
        private static final String TAG_DESCRIPTION = "description";
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.edit_product);
     
            // save button
            btnSave = (Button) findViewById(R.id.btnSave);
            btnDelete = (Button) findViewById(R.id.btnDelete);
     
            // getting product details from intent
            Intent i = getIntent();
     
            // getting product id (pid) from intent
            pid = i.getStringExtra(TAG_PID);
     
            // Getting complete product details in background thread
            new GetProductDetails().execute();
     
            // save button click event
            btnSave.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // starting background task to update product
                    new SaveProductDetails().execute();
                }
            });
     
            // Delete button click event
            btnDelete.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // deleting product in background thread
                    new DeleteProduct().execute();
                }
            });
     
        }
     
        /**
         * Background Async Task to Get complete product details
         * */
        class GetProductDetails extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditProductActivity.this);
                pDialog.setMessage("Loading product details. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Getting product details in background thread
             * */
            protected String doInBackground(String... params) {
     
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        // Check for success tag
                        int success;
                        try {
                            // Building Parameters
                            List<NameValuePair> params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair("pid", pid));
     
                            // getting product details by making HTTP request
                            // Note that product details url will use GET request
                            JSONObject json = jsonParser.makeHttpRequest(
                                    url_product_details, "GET", params);
     
                            // check your log for json response
                            Log.d("Single Product Details", json.toString());
     
                            // json success tag
                            success = json.getInt(TAG_SUCCESS);
                            if (success == 1) {
                                // successfully received product details
                                JSONArray productObj = json
                                        .getJSONArray(TAG_PRODUCT); // JSON Array
     
                                // get first product object from JSON Array
                                JSONObject product = productObj.getJSONObject(0);
     
                                // product with this pid found
                                // Edit Text
                                txtName = (EditText) findViewById(R.id.inputName);
                                txtPrice = (EditText) findViewById(R.id.inputPrice);
                                txtDesc = (EditText) findViewById(R.id.inputDesc);
     
                                // display product data in EditText
                                txtName.setText(product.getString(TAG_NAME));
                                txtPrice.setText(product.getString(TAG_PRICE));
                                txtDesc.setText(product.getString(TAG_DESCRIPTION));
     
                            }else{
                                // product with pid not found
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once got all details
                pDialog.dismiss();
            }
        }
     
        /**
         * Background Async Task to  Save product Details
         * */
        class SaveProductDetails extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditProductActivity.this);
                pDialog.setMessage("Saving product ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Saving product
             * */
            protected String doInBackground(String... args) {
     
                // getting updated data from EditTexts
                String name = txtName.getText().toString();
                String price = txtPrice.getText().toString();
                String description = txtDesc.getText().toString();
     
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair(TAG_PID, pid));
                params.add(new BasicNameValuePair(TAG_NAME, name));
                params.add(new BasicNameValuePair(TAG_PRICE, price));
                params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
     
                // sending modified data through http request
                // Notice that update product url accepts POST method
                JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                        "POST", params);
     
                // check json success tag
                try {
                    int success = json.getInt(TAG_SUCCESS);
     
                    if (success == 1) {
                        // successfully updated
                        Intent i = getIntent();
                        // send result code 100 to notify about product update
                        setResult(100, i);
                        finish();
                    } else {
                        // failed to update product
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once product uupdated
                pDialog.dismiss();
            }
        }
     
        /*****************************************************************
         * Background Async Task to Delete Product
         * */
        class DeleteProduct extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditProductActivity.this);
                pDialog.setMessage("Deleting Product...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Deleting product
             * */
            protected String doInBackground(String... args) {
     
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("pid", pid));
     
                    // getting product details by making HTTP request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_delete_product, "POST", params);
     
                    // check your log for json response
                    Log.d("Delete Product", json.toString());
     
                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // product successfully deleted
                        // notify previous activity by sending code 100
                        Intent i = getIntent();
                        // send result code 100 to notify about product deletion
                        setResult(100, i);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once product deleted
                pDialog.dismiss();
     
            }
     
        }
    }
    JSONParser.java
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    public class JSONParser {
     
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
     
        // constructor
        public JSONParser() {
     
        }
     
        // function get json from url
        // by making HTTP POST or GET mehtod
        public JSONObject makeHttpRequest(String url, String method,
                List<NameValuePair> params) {
     
            // Making HTTP request
            try {
     
                // check for request method
                if(method == "POST"){
                    // request method is POST
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
     
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
     
                }else if(method == "GET"){
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);
     
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }           
     
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
     
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
     
            // return JSON String
            return jObj;
     
        }
    }
    code get_product_details.php
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    <?php
     
    /*
     * Following code will get single product details
     * A product is identified by product id (pid)
     */
     
    // array for JSON response
    $response = array();
      header('Content-Type: text/html; charset=UTF-8');
    try
    {
        $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        $pdo_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
        $bdd = new PDO('mysql:host=localhost;dbname=test', 'xxxxx', 'xxxx', $pdo_options);
    }
    catch (PDOException $e)
    {
        die('Erreur : ' . $e->getMessage());
    }
     
     
     
    // check for post data
    if (isset($_GET["pid"])) {
        $pid = $_GET['pid'];
     
        // get a product from products table
        $result = $bdd->prepare("SELECT *FROM products WHERE pid = :pid");
    	$result->bindValue(':pid', $pid, PDO::PARAM_INT);
    	$result->execute;
    $products = $req->fetchAll(PDO::FETCH_ASSOC);  
    $total_products = count($products);
     
    // check for empty result
        // looping through all results
        // products node
        $response["products"] = array();
        $cpt = 0;
        foreach ($products as $product) {
     
            // temp user array
            // push single product into final response array
            array_push($response["products"], $product);
    		$cpt++;
        }
        // success
        $response["success"] = 1;
     
        // echoing JSON response
        echo json_encode($response);
    }
    ?>

    Le rapport LogCat est dans les images "capture" puis "capture1" ci-jointes.

    Pouvez vous m-aider? merci
    Images attachées Images attachées   

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Amazon Web Service] Signature requête
    Par aurelienl dans le forum Bibliothèques et frameworks
    Réponses: 9
    Dernier message: 30/09/2009, 10h32
  2. Projet Web + .Net, Web services : problème d'arguments
    Par Freud44 dans le forum Général Dotnet
    Réponses: 1
    Dernier message: 19/08/2009, 10h03
  3. Web Service : problème de serialisation d'objets
    Par cfeltz dans le forum Silverlight
    Réponses: 2
    Dernier message: 25/05/2009, 15h10
  4. Réponses: 10
    Dernier message: 26/08/2008, 10h00
  5. Web Services - Problème de communication serveur/client
    Par vern's dans le forum Web & réseau
    Réponses: 9
    Dernier message: 27/08/2007, 10h06

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo