Set the header value to JSONObject during Android Http communication

Asked 2 years ago, Updated 2 years ago, 28 views

It's exactly what the title is. Even if I search it, when I set the header value, You can only put (String, String) in setRequestProperty. Is there a way to request it by putting it in JSON format? It's not the body part, but the header part.

android

2022-09-22 20:43

1 Answers

String jsonData= "{\"name\":\"sunwookim\",\"age\":26,\"position\":\"Developer\"}";

setRequestProperty("jsonData", jsonData);

In this way, you can send it as a string value with the form of json. (There are many other ways to string json data than above.)

I'll have to parse on the server, though.

Below is an example. I used the okhttp library with gson.

The methods are different, but the principles are the same.

Client :

       HttpUrl httpUrl = new HttpUrl.Builder()
                .scheme("http")
                .host(url)
                .port(8081)
                .addPathSegment("test")
                .build();

        Request post = new Request.Builder()
                .url(httpUrl)
                .header("jsonData", "{\"name\":\"sunwookim\",\"age\":26,\"position\":\"Developer\"}")
                .build();

        getResponse(post);

Server :

        String jsonData = request.getHeader("jsonData");
        JsonElement contents = new JsonParser().parse(jsonData);
        System.out.println(contents.getAsJsonObject().get("name").getAsString());
        System.out.println(contents.getAsJsonObject().get("age").getAsInt());
        System.out.println(contents.getAsJsonObject().get("position").getAsString());


2022-09-22 20:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.