Monday, April 17, 2017

How to access transport headers inside the custom message formatter.

Find the blow custom formatter class and you can see the way we access the transport headers.

package com.wso2.sample.formatter;

import org.apache.axiom.om.OMOutputFormat;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.MessageFormatter;

import java.io.OutputStream;
import java.net.URL;
import java.util.Map;
import java.util.Set;

public class CustomMessageFormatter implements MessageFormatter {

    public void writeTo(MessageContext messageContext, OMOutputFormat omOutputFormat, OutputStream outputStream, boolean b) throws AxisFault {
        Map headerMap = (Map) messageContext.getProperty(MessageContext.TRANSPORT_HEADERS);
        Set keySet = headerMap.keySet();
        for (String key : keySet) {
            System.out.println(key + " >> " + headerMap.get(key));
        }
    }

    public String getContentType(MessageContext messageContext, OMOutputFormat omOutputFormat, String s) {
        return null;
    }

    public URL getTargetAddress(MessageContext messageContext, OMOutputFormat omOutputFormat, URL url) throws AxisFault {
        return null;
    }

    public String formatSOAPAction(MessageContext messageContext, OMOutputFormat omOutputFormat, String s) {
        return null;
    }

    public byte[] getBytes(MessageContext messageContext, OMOutputFormat omOutputFormat) throws AxisFault {
        return new byte[0];
    }
}

Note: You can get the transport headers using getProperty(MessageContext.TRANSPORT_HEADERS). Transport headers comes as key and value pairs (Map).

According to the above sample you can print the headers as below

Accept >> */*
Accept-Encoding >> gzip, deflate
Accept-Language >> en-US,en;q=0.8
Cache-Control >> no-cache
Content-Type >> application/xml
Host >> tharanga:8280
Origin >> chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Postman-Token >> 8e78f643-842c-175a-69c0-3a94e1ba1950
Sample-Custom-header >> Test value

No comments:

Post a Comment