George
George

Reputation: 333

Passing String parameter and object in Post request to a RESTful service

I have a client side method:

@SuppressWarnings("unchecked")
public static void main(String[] args){
    mediaTracker = new MediaTracker(frame);

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setSize(dim.width, dim.height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    setFullScreen();

    RSACipher rsaCipher = new RSACipher();
    // client side code
    RSAKeyPair keyPair;
    try {
        keyPair = new RSAKeyPair(2048);

        String servletURL = "http://localhost:8080/AesRsaEncryptionServiceRest/aesrsarest/doc/encryptionservice?pkey=pkey&skey=skey";

        Gson gson = new GsonBuilder().create();

        URL servlet = null;
        try {

            servlet = new URL(servletURL);
            System.out.println("Sending request to " + servletURL);
            HttpURLConnection servletConnection = (HttpURLConnection) servlet.openConnection();
            servletConnection.setRequestMethod("POST");
            servletConnection.setDoOutput(true);
            servletConnection.setDoInput(true);


            //send the keys to the server
            ObjectOutputStream objOut = new ObjectOutputStream(servletConnection.getOutputStream());

            objOut.writeObject(keyPair.getPublicKey());

            objOut.flush();
            objOut.close();

In line ObjectOutputStream objout, I passed the publickey needed for encryption. I want to know, if it's possible to pass a String parameter with object to post method?

I tried to create a new object, then I put the String parameters and the public key object and passed to an object stream, but it did not work. I needed the String parameters for passing the filename to be encrypted using the RESTful service

Upvotes: 0

Views: 3367

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30819

Assuming it's a json request, we can use any json parser (i.e. Gson, Jackson etc) to convert object into json and POST it to url. Below is an example to pass a Map(object) using Jackson.

OutputStreamWriter out = new   OutputStreamWriter(servletConnection.getOutputStream());
ObjectMapper mapper = new ObjectMapper(); //Jackson Object mapper
Map<String, Object> data = new HashMap<String, Object>();
data.put("key", "value");
out.write(mapper.writeValueAsString(data));

Similarly, we can convert any object into json and send it in payload.

Upvotes: 1

Related Questions