Reputation: 1868
I am trying to use the following JAVA code to send some data to Firebase Realtime Database using REST API.
public void doWork() {
consumer.subscribe(Collections.singletonList(this.topic));
ConsumerRecords<String, String> records = consumer.poll(1000);
for (ConsumerRecord<String, String> record : records) {
System.out.println("Sending data: " + record.value() );
// https://testiosproject-6054a.firebaseio.com/users.json
// 1. URL
URL url;
try {
url = new URL("https://testiosproject-1234a.firebaseio.com/users.json");
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
// 3. Specify POST method
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.connect();
// Write data
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(record.value());
osw.flush();
osw.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The following is the data trying to send:
Sending data: {"UserID":"101","UserAddress":"XYZ","UserAccount":"987","UserName":"Stella"}
But, I am not getting this data received on Firebase Realtime database console. I am not sure what could be the reason for this issue?
I tried Postman client and tried the same URL and data, it works fine.
Could someone guide me to fix this issue?
Upvotes: 4
Views: 905
Reputation: 643
I'd go with a lib that abstracts some of these things such as CXF (for the actual HTTP stuff) and Jackson (for JSON handling). The code would be made much simpler:
WebClient client = WebClient.create("https://testiosproject-1234a.firebaseio.com");
client.path("users.json");
client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
Response r = client.post(record);
MyResponseClassIfAny b = r.readEntity(MyResponseClassIfAny .class);
Adapted from CXF Documentation.
Note that most of the WebClient setup code could (and probably should) be done outside the fr loop since it never changes.
Upvotes: 1