java json post request using HttpURLConnection with nodejs server

I’m trying to do a JSON post request using java HttpURLConnection, I see a lot of tutorials, and nothing works with me; when I send data from java to NodeJs server the data become null or no data are received, and I don’t know if the problem with the API or how I send data from java.

Java function:

 public static void executePostHttp(String targetURL) {
        HttpURLConnection connection = null;
        String json = "{"voiceprints": [512.232.4454] }";

        try

        {
            // targetURL= http://localhost:3000;
            URL url = new URL(targetURL + "/1/v");

            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // Request setup
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setConnectTimeout(50000);
            con.setReadTimeout(50000);

            OutputStream os = con.getOutputStream();
            byte[] input = json.getBytes("utf-8");
            // System.out.println("input: " + input);
            os.write(input, 0, input.length);
            // read the respons
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            StringBuilder response = new StringBuilder();
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            System.out.println(response.toString());

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

    }

NodeJs:

router.post('/:id/v', async (req, res, next) => {
    try {
        const { id } = req.params;

        console.log(req.body);
        const value = req.body.voiceprints;
        console.log(value);
        const item = await House.findOne({
            "_id": id
        })
        if (!item) return next();
        item.voiceprints.push(value);
        const update = await House.updateOne({ "_id": id }, { "voiceprints": item.voiceprints });
        res.json(update);
    } catch (error) {
        next(error);
    }
});

I test the API with the postman and its work without any problem.

Answer

After trying and testing, I finally solveed the problem!

I use HttpClient instead of HttpURLConnection it more cleaner and easer to use.

first import the libraries:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

then the java function becomes:

  public static void executePostJson(String targetURL) throws Exception {

        HttpClient httpClient = HttpClientBuilder.create().build();
        String json = "voiceprints=[4554,4545]"; //=> {voiceprints:"[4554,4545]"} json
        try {
            HttpPost request = new HttpPost(targetURL + "/1/v");
            StringEntity params = new StringEntity(json);
            request.addHeader("content-type", "application/x-www-form-urlencoded");
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);
            System.out.println(response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
           
        }
    }

and I change how I received the data (JSON) in NodeJs:

        let value = req.body.voiceprints;
        value = JSON.parse(value);// convart the string value to array 

Leave a Reply

Your email address will not be published. Required fields are marked *