3

Friends!

I have a simple HTTP request:

void postRequest(String postUrl,String phone, String message) throws IOException {

    OkHttpClient client = new OkHttpClient();

    //RequestBody body = RequestBody.create(JSON, postBody);
    RequestBody body = new FormBody.Builder()
            .add("phone", phone)
            .add("message", message)
            .build();

    Request request = new Request.Builder()
            .url(postUrl)
            .post(body)
            .build();
    //System.out.println(request);

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            call.cancel();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("TAG",response.body().string());
        }
    });
}

How to properly implement sending a JSON object instead of simple parameters? My attempts were unsuccessful, so I really need a hint.

The server that will accept JSON is running on AKKA-HTTP. How do I send a request to this server correctly?

final case class Message(phone: String, message: String, service: String)
  implicit val item = jsonFormat3(Message)
  val queue: Queue[Message] = Queue()

val addMessage = post {
      path("add_message"){
        parameters("phone".as[String], "message".as[String], "service".as[String]){
          (phone, message, service) => {
            queue.enqueue(Message(phone, message, service))
            complete("ok")
          }
        }
      }
    }
Mardaunt
  • 82
  • 1
  • 13

2 Answers2

0

The easiest way to map and serialize your object in JSON format is to use the ObjectMapper class of jackson-databind library.

I personally use it to implement integration tests of RestControllers and it works very well. Here is the utility class I realized, you can take it and use it for your purposes:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class JsonUtils {

    public static String json(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(obj);
    }
}

What you need to have is a POJO class which implements Serializable, and then pass the instance of your class to the json method and it will return the JSON format.

You can definitely use it for Android projects. I found many examples where you can add the dependency, but it depends whether you use Gradle or Maven.

Try that out!!!

Marco Tizzano
  • 1,726
  • 1
  • 11
  • 18
0

How do you like this option? I tried to implement it, but the send fails. I'm missing an important detail. But I don't understand what it is.

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

  OkHttpClient client = new OkHttpClient();
  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  // put your json here
  RequestBody body = RequestBody.create(JSON, jsonObject.toString());
  Request request = new Request.Builder()
                    .url("https://YOUR_URL/")
                    .post(body)
                    .build();

  Response response = null;
  try {
      response = client.newCall(request).execute();
      String resStr = response.body().string();
  } catch (IOException e) {
      e.printStackTrace();
  }
Mardaunt
  • 82
  • 1
  • 13