![](/img/trans.png)
[英]What is the best approach to update a document in cloudant if available or else insert the document using Java cloudant 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.