1

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

如果有人以前这样做过,将不胜感激。谢谢。

4

1 回答 1

0

Ok so I managed to make it work. Here is the code I've used:

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();
       }
于 2013-06-19T12:26:01.593 回答