javaapihttppostnimble

API call by HTTP POST method without using parameter name for the body


I'm using Java. How I can make a HTTP POST call API and inform in body only "JSON" value (without parameter name)?

Per example call this URL: https://api.nimble.com/api/v1/contact?access_token=12123486db0552de35ec6daa0cc836b0 (POST METHOD) and in body would only have this (without parameter name):

{'fields':{'first name': [{'value': 'Jack','modifier': '',}],'last name': [{'value': 'Daniels','modifier': '',}],'phone': [{'modifier': 'work','value': '123123123',}, {'modifier':'work','value': '2222',}],},'type': 'person','tags': 'our customers\,best'}

If this is correct, someone could give me an example please?


Solution

  • Using this library for the network part : http://hc.apache.org/

    Using this library for the json part : http://code.google.com/p/google-gson/

    Example :

    public String examplePost(DataObject data) {
            HttpClient httpClient = new DefaultHttpClient();
    
            try {
                HttpPost httppost = new HttpPost("your url");
                // serialization of data into json
                Gson gson = new GsonBuilder().serializeNulls().create();
                String json = gson.toJson(data);
                httppost.addHeader("content-type", "application/json");
    
                // creating the entity to send
                ByteArrayEntity toSend = new ByteArrayEntity(json.getBytes());
                httppost.setEntity(toSend);
    
                HttpResponse response = httpClient.execute(httppost);
                String status = "" + response.getStatusLine();
                System.out.println(status);
                HttpEntity entity = response.getEntity();
    
                InputStream input = entity.getContent();
                StringWriter writer = new StringWriter();
                IOUtils.copy(input, writer, "UTF8");
                String content = writer.toString();
                // do something useful with the content
                System.out.println(content);
                writer.close();
                EntityUtils.consume(entity);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
    

    Hope it helps.