How to create a database in CouchDB with username and password

I am creating an Android application that stores data in CouchDB, and I need to create a database from an Android application. I need to execute the command "curl-X PUT http: // user: passwd@127.0.0.1 : 5984 / myDataBase " using java methods.

I implemented the following functions:

public static boolean createDatabase(String hostUrl, String databaseName) { try { HttpPut httpPutRequest = new HttpPut(hostUrl + databaseName); JSONObject jsonResult = sendCouchRequest(httpPutRequest); return jsonResult.getBoolean("ok"); } catch (Exception e) { e.printStackTrace(); } return false; } private static JSONObject sendCouchRequest(HttpUriRequest request) { try { HttpResponse httpResponse = (HttpResponse) new DefaultHttpClient().execute(request); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String resultString = convertStreamToString(instream); instream.close(); JSONObject jsonResult = new JSONObject(resultString); return jsonResult; } } catch (Exception e) { e.printStackTrace(); } return null; } 

I call the function:

 createDatabase("http://user: passwd@127.0.0.1 /","myDataBase"); 

but there is no result. I think the problem is in the user: passwd, because in the "admin party" mode the function works fine, calling:

 createDatabase("http://127.0.0.1/","myDataBase"); 
+4
source share
2 answers

I had the same problem -> you need to use HTTP authentication in the header. So just add these header lines to your query:

 private static void setHeader(HttpRequestBase request) { request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); request.setHeader("Authorization", "Basic base64(username:password)"); } 

Keep in mind that you need to encode the phrase "username: password" on base64. it looks something like this:

 request.setHeader("Authorization", "Basic 39jdlf9udflkjJKDKeuoijdfoier"); 
+4
source

You can watch this blog post on libcouch-android . It has some interesting features that really support Android development with CouchDB. For example, automatic creation of databases and passwords for applications, so users have transparent use of CouchDB (if necessary).

In addition, it offers access to CouchDB's RPC methods, so you can start and stop the database from the life cycles of your application.

As for security, I just added this to this thread .

0
source

Source: https://habr.com/ru/post/1347739/


All Articles