簡體   English   中英

為什么此Cloudant Java API代碼不更新現有數據庫記錄?

[英]Why does this Cloudant java api code not update existing database record?

我寫了這段代碼來更新現有的數據庫記錄。 它返回沒有錯誤,但不更新記錄。 我確保“ _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");
    }
}

我認為您的網址不正確。

您正在使用基本身份驗證標頭正確發送憑據-不應將其直接包含在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");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM