Search code examples
javascalahttprestavro

java example for sending avro/bytes POST request to server


I'm interested in sending avro/bytes (raw bytes) in POST request into a server. Before handcoding anything of my own i wanted to check out some ready made example and found none yet.. Anyone has any example of how to send avro/bytes encoded POST request body into a server? (bytes encoded into avro/bytes but not to base64 etc)


Solution

  • convert your object to avro and then to bytes and then you can use this simple method(using apache httpcore) to get the response (this method assumes that the server response with json string)

     public static String postJSON(String uri, byte[] req) {
        String queryResponse = null;
        try {
            List<Header> httpHeaders = new ArrayList<Header>();
            httpHeaders.add(HttpClientUtil.ACCEPT_TEXT_HTML);
            HttpResponse response = HttpClientUtil.post(uri, req, ContentType.DEFAULT_BINARY, httpHeaders);
            HttpEntity entity = response.getEntity();
    
            queryResponse = EntityUtils.toString(entity);
    
        } catch (ClientProtocolException e) {
            logger.log(java.util.logging.Level.SEVERE, e.getMessage(), e);
        } catch (IOException e) {
            logger.log(java.util.logging.Level.SEVERE, e.getMessage(), e);
        }
    
        return queryResponse;
      }