4

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:passwd@127.0.0.1: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:passwd@127.0.0.1/","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");
4

2 回答 2

4

我遇到了同样的问题->您必须在标头中使用 HTTP 身份验证。因此,只需将此标题行添加到您的请求中:

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

请记住,您必须使用 base64 对短语“用户名:密码”进行编码。这看起来像这样:

request.setHeader("Authorization", "Basic 39jdlf9udflkjJKDKeuoijdfoier");
于 2011-04-13T12:30:30.297 回答
0

你可以看看libcouch-android 上的这篇博文。它有一些很好的特性,真正支持使用 CouchDB 进行 Android 开发。例如自动为应用程序创建数据库和密码,这样用户就可以透明地使用 CouchDB(如果需要)。

此外,它还提供对 CouchDB 的 RPC 方法的访问,因此您可以在应用程序的生命周期中启动和停止 DB。

关于安全性,我刚刚在此线程中对此进行了总结。

于 2011-04-16T16:22:20.710 回答