2013-06-13 4 views
1

J'ai une base de données CouchDB sur iriscouch.com. Je travaille sur une application Android.Comment créer un document simple dans une base de données CouchDB à partir d'Android?

J'ai été bloqué une tâche simple: de faire un document dans une base de données à partir d'Android. J'essaie de le faire d'une manière simple (c'est-à-dire sans utiliser les bibliothèques DroidCouch).

Note: J'ai essayé de créer une base de données CouchDB par HTTP POST (que l'on trouve sur un autre sujet de StackOverflow) et cela a fonctionné.

Voici où je suis parti de mon travail:

public void postData2() { 

     new Thread(new Runnable() 
     { 
      //Thread to stop network calls on the UI thread 
      public void run() { 
       // Create a new HttpClient and Post Header 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost("http://2bm.iriscouch.com/test2"); 

       try { 
        System.out.println("Reaching CouchDB..."); 

        // Add your data 
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
        nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi")); 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

        // Execute HTTP Post Request 
        HttpResponse response = httpclient.execute(httppost); 
        System.out.println(response.toString()); 

        System.out.println("Execurting HTTP Post..."); 
        // Execute HTTP Post Request 
        ResponseHandler<String> responseHandler = new BasicResponseHandler(); 

        String responseBody = httpclient.execute(httppost, responseHandler); 

        JSONObject responseJSON = new JSONObject(responseBody); 
        System.out.println("Response: " + responseJSON.toString()); 
       } catch (ClientProtocolException e) { 
        e.printStackTrace(); 
        // TODO Auto-generated catch block 
       } catch (IOException e) { 
        e.printStackTrace(); 
        // TODO Auto-generated catch block 
       } 
      } 
     }).start(); 
    } 

Si quelqu'un avait fait cela auparavant, une aide serait appréciée. Merci.

+0

Avez-vous une réponse? – HeatfanJohn

+0

Quel est le problème que vous rencontrez? Créez un objet JSON et placez-le dans le corps de la requête POST comme indiqué dans les documents: http://wiki.apache.org/couchdb/HTTP_Document_API#POST. – WiredPrairie

+0

Merci, je vais essayer et vous savez comment cela fonctionne. – msysmilu

Répondre

0

Ok, donc j'ai réussi à le faire fonctionner. Voici le code que j'ai utilisé:

public static String createDocument(String hostUrl, String databaseName, JSONObject jsonDoc) { 
       try { 
        HttpPut httpPutRequest = new HttpPut(hostUrl + databaseName); 
        StringEntity body = new StringEntity(jsonDoc.toString(), "utf8"); 
        httpPutRequest.setEntity(body); 
        httpPutRequest.setHeader("Accept", "application/json"); 
        httpPutRequest.setHeader("Content-type", "application/json"); 
        // timeout params 
        HttpParams params = httpPutRequest.getParams(); 
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.valueOf(1000)); 
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.valueOf(1000)); 
        httpPutRequest.setParams(params); 

        JSONObject jsonResult = sendCouchRequest(httpPutRequest); 
        if (!jsonResult.getBoolean("ok")) { 
          return null; 
        } 
        return jsonResult.getString("rev"); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       return null; 
     } 


private static JSONObject sendCouchRequest(HttpUriRequest request) { 
       try { 
        HttpResponse httpResponse = (HttpResponse) new DefaultHttpClient().execute(request); 
        HttpEntity entity = httpResponse.getEntity(); 
        if (entity != null) { 
          // Read the content stream 
          InputStream instream = entity.getContent(); 
          // Convert content stream to a String 
          String resultString = convertStreamToString(instream); 
          instream.close(); 
          // Transform the String into a JSONObject 
          JSONObject jsonResult = new JSONObject(resultString); 
          return jsonResult; 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       return null; 
     } 


public static String convertStreamToString(InputStream is) { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192); 
       StringBuilder sb = new StringBuilder(); 

       String line = null; 
       try { 
        while ((line = reader.readLine()) != null) { 
          sb.append(line + "\n"); 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } finally { 
        try { 
          is.close(); 
        } catch (IOException e) { 
          e.printStackTrace(); 
        } 
       } 
       return sb.toString(); 
     } 
Questions connexes