Search code examples
javasslwebclient

Java webclient returns 2 double quotes on string response


package com.myproject.extract.Generic;

import com.myproject.extract.Callbacks.catchError;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;

import org.bson.types.ObjectId;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;

import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

public class ajax {

    public static Mono<String> Post(String url, ObjectId projectId, JsonObject data) {
        try {
            // To call https, following is required.
            SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();

            HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext));

            WebClient webClient = WebClient.builder().baseUrl("https://localhost:3100/api/" + url)
                    .defaultHeader("projectId", projectId.toString()) // TODO: there was option of only header instead
                                                                        // of
                                                                        // defaultheader. don't know why that was not
                                                                        // working. don't know the difference either.
                    .clientConnector(new ReactorClientHttpConnector(httpClient)).build();

            return webClient.post().syncBody(toJsonNode(data)).retrieve().bodyToMono(String.class);
        } catch (Exception e) {
            catchError.handlError(e);
        }
        return null;
    }

    public static JsonNode toJsonNode(JsonObject jsonObj) throws Exception {
        return new ObjectMapper().readTree(jsonObj.toString());
    }

}

I am using above method as following.

enter image description here

As you can see response shows 2 double quotes for string value. Because of this I am unable to parse it to ObjectID.

What wrong am I doing?

Why it returns 2 double quoted value ""60cc845e86114119f8aa4306"" instead of 1 double quoted value "60cc845e86114119f8aa4306"?

How to prevent 2 double quoted value and retrieve 1 double quoted value?


Solution

  • Looks like when I return JSON response and I use bodyToMono(String.class), it stringifies that.

    When I return string from the server, bodyToMono(String.class) stringifies that as well and adds extra quotes. For now, I have removed it manually using substring.