2013-06-13 2 views
1

나는 irouchouch.com에 CouchDB 데이터베이스를 가지고 있습니다. Android 앱에서 작업하고 있습니다.Android에서 CouchDB 데이터베이스에 간단한 문서를 만드는 방법은 무엇입니까?

간단한 작업이 필요했습니다. 안드로이드에서 데이터베이스에 문서를 만드는 것입니다. 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(); 
    } 

, 도움 주시면 감사하겠습니다 : 여기

내가 내 일을 그만 둔 곳입니다. 감사.

+0

어떤 응답이 있습니까? – HeatfanJohn

+0

발생하는 문제점은 무엇입니까? JSON 객체를 빌드하고 docs : http://wiki.apache.org/couchdb/HTTP_Document_API#POST에 표시된대로 POST 요청의 본문에 넣습니다. – WiredPrairie

+0

고마워, 나는 그것을 시도하고 어떻게 작동하는지 알게 될거야. – msysmilu

답변

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(); 
     } 
관련 문제