juancar
juancar

Reputation: 41

How to create a database in CouchDB indicating the username and password

I´m creating an android application that stores data in CouchDB, and I need to create a database from the android application. I need to execute the command "curl-X PUT http://user:[email protected]:5984/myDataBase" with java methods.

I have 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 by:

createDatabase("http://user:[email protected]/","myDataBase");

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

createDatabase("http://127.0.0.1/","myDataBase");

Upvotes: 4

Views: 1294

Answers (2)

chris polzer
chris polzer

Reputation: 3367

You could have a look at this blogpost on libcouch-android. It has some nice features that really support Android development with CouchDB. For example automatically creating databases and passwords for applications, so users have transparent usage of CouchDB (if wanted).

Also, it is offering access to the RPC methods of CouchDB, so you can start and stop the DB from your application's lifecycles.

Regarding security, I just had this summed up here in this thread.

Upvotes: 0

stegasius
stegasius

Reputation: 41

I had the same problem -> you have to use the HTTP Authentication in the header. So just add this header lines to your request:

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 have to encode the phrase "username:password" with base64. this looks something like this:

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

Upvotes: 4

Related Questions