Explicit Java data transfer using Firebase Realtime database using REST API

I am trying to use the following JAVA code to send some data to a Firebase Realtime database using the 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 are data trying to send:

 Sending data: {"UserID":"101","UserAddress":"XYZ","UserAccount":"987","UserName":"Stella"} 

But I do not get this data on the Firebase Realtime database console. I'm not sure what is the cause of this problem?

I tried the mail client and tried the same URL and data, it works fine.

Can someone help me solve this problem?

+5
source share
1 answer

I would go with lib, which abstracts some of these things, such as CXF (for the actual HTTP material) and Jackson (for handling JSON). The code will be 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 configuration code can (and probably should) be executed outside of the fr loop, since it never changes.

+1
source

Source: https://habr.com/ru/post/1275533/


All Articles