为什么这个Cloudant java api代码不会更新现有的数据库记录?

时间:2014-08-25 18:26:38

标签: java cloudant

我编写了这段代码来更新现有的数据库记录。它返回时没有错误但不更新记录。我确保“_rev”和“_id”参数与最新读取相同并验证它。这段代码有什么特别的错误吗?

private void updateUserInfo(String dataTmp) {
    try {
        JSONObject newObj = new JSONObject(dataTmp);
        String data = newObj.toString();
        System.out.println("About to add the following string to database: " + data);
        URL url = new URL("https://abc:xyz@pqr.cloudant.com:443/databaseName/");

        HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("POST");
        final String encodedUserPass = new String(Base64.encodeBase64(("abc" + ":" + "abc").getBytes()));

        @SuppressWarnings("deprecation")
        String encodedData = URLEncoder.encode(data);
        httpCon.setRequestProperty("Content-type", "application/json");
        httpCon.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        httpCon.setRequestProperty("Authorization", "Basic " + encodedUserPass);

        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write(data);
        out.close();

        Runtime.getRuntime().gc();

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error while updating the user record");
    }
}

1 个答案:

答案 0 :(得分:2)

我认为您的网址不正确。

您正在使用基本身份验证标头正确发送凭据 - 它们不应直接包含在URL中。一些HTTP库/实用程序(例如cURL)具有以下功能:它们解析URL中的凭据并将其转换为基本的auth标头,但是当使用大多数标准HTTP库时,您必须自己执行此操作。以下应该有效:

private void updateUserInfo(String dataTmp) {
    try {
        JSONObject newObj = new JSONObject(dataTmp);
        String data = newObj.toString();
        System.out.println("About to add the following string to database: " + data);
        URL url = new URL("https://pqr.cloudant.com/databaseName/");

        HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("POST");
        final String encodedUserPass = new String(Base64.encodeBase64(("abc" + ":" + "abc").getBytes()));

        @SuppressWarnings("deprecation")
        String encodedData = URLEncoder.encode(data);
        httpCon.setRequestProperty("Content-type", "application/json");
        httpCon.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        httpCon.setRequestProperty("Authorization", "Basic " + encodedUserPass);

        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write(data);
        out.close();

        Runtime.getRuntime().gc();

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error while updating the user record");
    }
}