如何在Android的CouchDB数据库中创建一个简单的文档?

时间:2013-06-13 13:11:06

标签: android couchdb http-post

我在iriscouch.com上有一个CouchDB数据库。我正在开发Android应用程序。

我遇到了一个简单的任务:在Android数据库中制作文档。 我试图以一种简单的方式(即不使用DroidCouch库)来做到这一点。

注意:我尝试通过HTTP POST创建一个CouchDB数据库(如StackOverflow中的其他主题所示)并且这样做有效。

这是我放弃工作的地方:

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

如果有人之前已经这样做了,一些帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

好的,所以我设法让它发挥作用。 这是我用过的代码:

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