Connecting to Daml JSON API

192 views Asked by At

I am stuck with this error. I don't know how to set the authorization header with a token.

Java code:

package URL;

import org.json.simple.JSONObject;
import sun.net.www.protocol.http.HttpURLConnection;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class DamlConnection {

    HttpURLConnection con;

    public DamlConnection() throws IOException {
        URL url = new URL("http://localhost:7575/v1/exercise"); //URL

        try {
            con = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        con.setRequestMethod("POST");
        con.setDoOutput(true);

        byte [] out = "{\"templateId\":\"Iou:Iou\",\"payload\":{\"issuer\":\"Alice\",\"owner\": \"Alice\",\"currency\": \"USD\",\"amount\": \"999.99\",\"observers\": []\"}}" .getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        con.setFixedLengthStreamingMode(length);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        con.connect();
        try(OutputStream os = con.getOutputStream()) {
            os.write(out);
        }

        System.out.println(out);
    }

    public static void main(String[] args) throws IOException {
        new DamlConnection();
    }
}


HTTP JSON API Service error:

08-04-2022 14:59:40.619 [http-json-ledger-api-akka.actor.default-dispatcher-10] INFO  com.daml.http.Endpoints - Incoming POST request on http://localhost:7575/v1/exercise from unknown, context: {instance_uuid: "2b7c26b1-566c-423e-8ddc-bf586850e645", request_id: "ebd0867e-95ec-4a05-acfd-d9e1cf97e7ed"}
08-04-2022 14:59:40.635 [http-json-ledger-api-akka.actor.default-dispatcher-7] INFO  com.daml.http.Endpoints - Responding to client with HTTP 401 Unauthorized, context: {instance_uuid: "2b7c26b1-566c-423e-8ddc-bf586850e645", request_id: "ebd0867e-95ec-4a05-acfd-d9e1cf97e7ed"}
1

There are 1 answers

0
stefanobaghino On

The HTTP JSON API service requires a JSON Web Token (JWT) to be issued alongside every request, even if you are running in an insecure environment. Refer to the documentation for details on how to create a token for development purposes.