Search code examples
javaandroidokhttpapache-httpcomponents

setEntity equivalent in OkHttp - Android


I'm migrating from the Apache HTTP legacy client to OkHttp and I'm having some problems finding equivalences between both. A couple of days ago I asked about credentials in this same subject and now I'm stuck again:

In the old implementation I have this:

TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();
reqGen.setCertReq(true);

MessageDigest digest = MessageDigest.getInstance("SHA256");
digest.update(myData);

TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA256, digest.digest(), BigInteger.valueOf(100));

byte[] enc_req = request.getEncoded();

myHttpPost.setEntity(new ByteArrayEntity(enc_req));

The most relevant line is the last one (as the others just build the request and, lucky enough, I won't need to change them), which adds the entity to the HttpPost.

Checking this answer it seems the entity of a request is

the majority of an HTTP request or response, consisting of some of the headers and the body, if present. It seems to be the entire request or response without the request or status line

But this definition confuses me as I can't find the equivalence to something with "headers and the body" in OkHttp. What I've tried:

MediaType textPlain = MediaType.parse("text/plain; charset=utf-8");
RequestBody requestBody = RequestBody.create(textPlain, request.getEncoded().toString());
Request myNewRequest = (new Request.Builder()).url(urlString).post(requestBody).build();

But it didn't work (I'm getting a 500 from the server). Does anyone know the correct equivalence?


Solution

  • I finally found the answer: I can use the TimeStampRequest encoded as I did before, without any modification. The change is, as I thought, only for the setEntity.

    This is the request using OkHttp:

    MediaType textPlain = MediaType.parse("binary");
    RequestBody requestBody = RequestBody.create(textPlain, request.getEncoded());
    Request myNewRequest = (new Request.Builder()).url(urlString).post(requestBody).build;
    

    As you can see the only change from the previous code I tried is that I use binary as the MediaType, which make sense as we are sending a byte array (previously used ByteArrayEntity from the Apache client).

    Hope it helps somebody.