![](/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.