I have this piece of code written to update an existing database record. It returns with no error but does not update the record. I ensured that the "_rev" and "_id" parameter is the same as the latest read and verified it. Is there anything specifically wrong about this code?
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");
}
}
Your URL is incorrect, I think.
You are correctly sending your credentials using a Basic Authentication header - they should not be included directly in the URL. Some HTTP libraries / utilities (eg cURL) have a feature where they parse the credentials in the URL and convert them into a basic auth header but when using most standard HTTP libraries you will have to do this yourself. The following should work:
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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.