I send POST request to create some data resource on server. I get Response Code 201 - all is OK. But I also need to get 2 headers from the response. Those headers contain attributes of the created resource. I did not find the way how to do it using ConnectionRequest's API.
The class has readHeaders(connection) and getHeader(connection) protected methods. But I could not use them when I got the response - got an exception.
My code example is shown below:
ConnectionRequest reqresp = new ConnectionRequest () {
protected void buildRequestBody (java.io.OutputStream os) {
Logger.inst ().write ("buildRequestBody");
final String body = "Dummy Request Body"; // necessary for my request
try {
os.write (body.getBytes () );
}
catch (Exception ex) {
final String errMsg = ex.toString ();
Logger.inst ().write (errMsg);
throw new RuntimeException (errMsg);
}
}
protected void readResponse (InputStream input) throws IOException {
// Actually this method will not be called.
Logger.inst ().write ("readResponse");
String respText;
try {
respText = Util.readToString (input);
}
catch (Exception ex) {
final String errMsg = ex.toString ();
Logger.inst ().write (errMsg);
throw new RuntimeException (errMsg);
}
Logger.inst ().write (respText);
}
};
reqresp.setUrl ("MY SERVER URL");
reqresp.setPriority (ConnectionRequest.PRIORITY_HIGH);
reqresp.setPost (true);
reqresp.addRequestHeader ("header1", "val1");
reqresp.addRequestHeader ("Content-type", "application/json");
reqresp.addResponseCodeListener (new ActionListener () {
public void actionPerformed (ActionEvent ae) {
Logger.inst ().write ("ResponseCodeListener:");
Logger.inst ().write (ae.toString () );
if (ae instanceof NetworkEvent) {
NetworkEvent evt = (NetworkEvent)ae;
Logger.inst ().write ("message: " + evt.getMessage () );
Logger.inst ().write ("response code: " + evt.getResponseCode () );
}
}
});
reqresp.addResponseListener (
new ActionListener () {
public void actionPerformed (ActionEvent ae) {
Logger.inst ().write ("ResponseCodeListener:");
Logger.inst ().write (ae.toString () );
if (ae instanceof NetworkEvent) {
NetworkEvent evt = (NetworkEvent)ae;
Logger.inst ().write ("message: " + evt.getMessage () );
Logger.inst ().write ("response code: " + evt.getResponseCode () );
}
}
}
);
NetworkManager.getInstance ().addToQueue (reqresp);
I could not perform the task using the LWUIT's IO. But I did it easily using the MIDP's HTTPConnection and met no problems.
One small comment about the MIDP's HTTPConnection API. It's synchronous. So, I did not want to use it in the main GUI thread. Moreover, the API is low-level. So, I had to implement some kind of wrapper to hide the details and to execute HTTP request asynchronously in a separate thread.
Now one comment about the LWUIT's IO ConnectionRequest class. I found it programmer-unfriendly. It represents both a request and response. So, it's not clear what the methods are related to the request and what to the response.