Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

http - example of curl request with #param convert to Java POST request

I am creating API to send messages to SMS Server. API is based on HTTP and JSON. Documentation takes cURL as an example I need convert it to JAVA.

Request:

POST https://gateway_ip/api/send_sms

Example Request with #param:

curl -k --anyauth -u admin:admin -d
'{"text":"#param#","port":[2,3],"param":[{"number":"10086","te
xt_param":["bj"],"user_id":1},{"number":"10086",
"text_param":["ye"],"user_id":2}]}' -H "Content-Type:
application/json" https://gateway_ip/api/send_sms

First I create model that take phone number, massage text and setup port

class Model {
        private final String number;
        private final String port;
        private final String text;

        public Model(String number, String text) {
            this.number = number;
            this.port = "[0]";
            this.text = text;
        }

        public String getNumber() {
            return number;
        }

        public String getPort() {
            return port;
        }

        public String getText() {
            return text;
        }
    }

JSON generator:

private static String toJsonString(List<Model> model) {

        StringWriter jsonObjectWriter = null;
        try {
            com.fasterxml.jackson.core.JsonFactory jsonFactory = new com.fasterxml.jackson.core.JsonFactory();
            jsonObjectWriter = new StringWriter();
            JsonGenerator generator = jsonFactory.createGenerator(jsonObjectWriter);
            generator.setPrettyPrinter(new DefaultPrettyPrinter());

            generator.writeStartObject();
            generator.writeStringField("text", "#param#");
            generator.writeStringField("port", "[0]");
            toJsonString(generator, model);
            generator.writeEndObject();
            generator.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return jsonObjectWriter.toString();
    }

    private static void toJsonString(final JsonGenerator generator, final List<Model> model) throws IOException{

        generator.writeFieldName("param");
        generator.writeStartArray();
        for (final Model m : model) {
            generator.writeStartObject();
            generator.writeStringField("number", m.getNumber());
            toJsonString(generator, m.getText());
            generator.writeEndObject();
        }
        generator.writeEndArray();

    }

    private static void toJsonString(final JsonGenerator generator, String text) throws IOException{

        generator.writeFieldName("text_param");
        generator.writeStartArray();
        generator.writeString(text);
        generator.writeEndArray();

    }

Headers with authentication - I am not sure if I should include authentication.

private HttpHeaders createHeadersWithAuthentication() {

        String credentials = login + ":" + password;
        byte[] credentialsBytes = Base64.getEncoder().encode(credentials.getBytes());
        String base64Credentials = new String(credentialsBytes);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Credentials);
        return headers;
    }

Execution

public ResponseEntity sendSMSMessage(String phoneNumber, String message) {

        Model model = new Model(phoneNumber, message);
        List<Model> modelList = new ArrayList<>();
        modelList.add(model);
        String createJson = toJsonString(modelList);

        // "https://xx.xx.xx.xx/api/send_sms";
        String url = urlConfig;

        // "Content-Type: application/json"
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<String>(createJson, httpHeaders);

        return restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
    }

I am not sure what I did wrong. From command line example from doc working fine but from my Java Code there is no output. Nothing was send to Sms Server. From debuger Json looks fine.

Appreciate for any hints and correction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your Model class is incorrect. Take another look at the JSON in the curl command. Here, I've formatted it to better see:

{
    "text": "#param#",
    "port": [2, 3],
    "param": [{
        "number": "10086",
        "text_param": ["bj"],
        "user_id": 1
    }, {
        "number": "10086",
        "text_param": ["ye"],
        "user_id": 2
    }]
}

As you can see, it consists of 2 objects, with fields:

  • text, port, param
  • number, text_param, user_id

Your Model class fits neither:

  • number, port, text

So you needed 2 classes, e.g. like this:

class Request {
    private final String text;
    private final List<Integer> port;
    private final List<Param> param;

    // Constructor and getter methods here
}
class Param {
    private final String number;
    private final List<String> text_param;
    private final int user_id;

    // Constructor and getter methods here
}

You can of course use arrays instead of List, but it's more common to use List.

Notice how the Model class in the question had declared port as type String with value "[0]". That would become JSON "port": "[0]", not the "port": [0] that is needed.

Since you're using Jackson, you should use Databind, e.g. to generate the JSON used in the curl command:

Request request = new Request(
        "#param#",
        Arrays.asList(2, 3),
        Arrays.asList(new Param("10086", Arrays.asList("bj"), 1),
                      new Param("10086", Arrays.asList("ye"), 2))
);

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(request);
System.out.println(json);

Output

{"text":"#param#","port":[2,3],"param":[{"number":"10086","text_param":["bj"],"user_id":1},{"number":"10086","text_param":["ye"],"user_id":2}]}

Now try that with the rest of your code. I didn't even look at the rest, given the big discrepancy in the JSON payload itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...