简体   繁体   中英

Sending a JSON message using Java

I'm triying to send this json message:

{"ruido_exterior":0,"co2_exterior":0,"humedad_interior":0,"ruido_interior":0,"temperatura_exterior":0,"co_interior":0,"co2_interior":0,"co_exterior":0,"temperatura_interior":0,"pm_25":8,"pm_10":10,"humedad_exterior":0,"timestamp":1494978084000}

Code

public static void sendRequestPostRenam(JSONObject json) throws IOException, JSONException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        try {

            URIBuilder builder = new URIBuilder(Config.urlJSON).addParameter("access-token", Config.renamToken);

            HttpPost request = new HttpPost(builder.build());
            StringEntity params = new StringEntity(json.toString());

            request.setEntity(params);

            CloseableHttpResponse response = httpClient.execute(request);

            //<editor-fold defaultstate="collapsed" desc="PRUBEAS DEBUG">
            String content = EntityUtils.toString(response.getEntity());
            Log.debug(content);
            //</editor-fold>

            int statusCode = response.getStatusLine().getStatusCode();

            Log.debug("[STATUS:" + statusCode + "]");

        } catch (Exception ex) {
            Log.debug(ex.toString());
        } finally {
            httpClient.close();
        }
    }

The output of content is:

{"status":"error","info":{"timestamp":["Timestamp no puede estar vacío."]},"timestamp":1495068046}

The message says "Timestamp can't be empty" but in the varibale " params " the timestamp value is contained. The point it looks like the request object doesn't have this json values.

EDIT 1:

I'm going to explain what I need to do. I have to send some data to an API via Json. It has access-token authentification and if I use curl I don't have any problem sending the data:

curl -X POST -H 'Content-Type: application/json' -d '{"pm25": 35, "timestamp": 147805158}' https://api.com/data/insert?access-token= {Yoq3UGQqDKP4D1L3Y6xIYp-Lb6fyvavpF3Lm-8cD}

As a result of the last command the answer is:

{"status":"ok","info":[],"timestamp":1495072199}

Anything help will be really apreciated.

I am not able to comment yet on your post, so pasting query as an answer here.

If I haven't miss anything then content you are printing depends upon the handling and business logic defined in remote service you are calling. You should provide more details regarding your remote service.

Anyways you could try adding header of content type in you request HttpPost object. request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM