Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Contributor
bb_eibl
Posts: 26
Registered: ‎04-09-2013
My Device: not specified
My Carrier: not speciefied
Accepted Solution

httpConnection can´t send query, difficulties with setRequestProperty

I have diffiulties sending a query to a server over a httpConection.

Sending the request via a POST write(postdata) obviously does not work for my applixation. I use the simulator. I double checked the setRequestProperty settings by applying getRequestProperty. The Content-Length is returned as null, it should be 108 which was set by setRequestProperty.

 

 

 

I wanted to set "Content-Length" before posting the query string but I always get null as answer (getRequestProperty).

Content-Length is set to 108 by the "setRequestProperty, but the getRequestProperty returns null !!

Content-Length: param11 is "null"

 

All other parameters set by setRequestProperty are isentical to those of the getRequestProperty.

 

I include th erelevant code:

 byte b[] =new byte[2000];
                    long len = 0;
                    try {
                         dos = new DataOutputStream(httpConn.openOutputStream());
                        byte postdata [];
                        postdata=query.getBytes();
                        int i=postdata.length; 
                        httpConn.setRequestProperty("Content-Length","108");
                        String param12=String.valueOf(i);
                        String param11=httpConn.getRequestProperty("Content-Length");
                        String param13=httpConn.getRequestProperty("Content-Type");
                        String param14=httpConn.getRequestProperty("Connection");
                        httpConn.setRequestMethod(HttpConnection.POST);
                        
                         
                          dos.write(postdata,0,postdata.length);
                          
                         dos.flush();
                         dos.close();

 Thank´s for your help !   I am a little bit desperate to be frank.:smileymad:

Please use plain text.
Developer
RexDoug
Posts: 4,764
Registered: ‎07-21-2008
My Device: Not Specified

Re: httpConnection can´t send query, difficulties with setRequestProperty

My forst reaction is: get rid of the flush() andc close(). You  should be calling getResponse(), which flushes the write anyway (then waits for the response).

 

You don't show ehere you "get" the "null" Content-Length header - I would say that if you set it, it's there.

Please use plain text.
Developer
peter_strange
Posts: 19,598
Registered: ‎07-14-2008
My Device: Not Specified

Re: httpConnection can´t send query, difficulties with setRequestProperty

Here is what I would code:

 

                        OoutputStream os = httpConn.openOutputStream();
                        byte postdata [];
                        postdata=query.getBytes();
                        httpConn.setRequestProperty("Content-Length", Integer.toString(postdata.length);
                        httpConn.setRequestMethod(HttpConnection.POST);
                        os.write(postdata,0,postdata.length);
                        os.flush();
                        os.close();

 

This will set the content length correctly for your Server to process. 

 

You should, as RexDoug suggested, then use getResponse() to find out what the Server made of your data. 

 

I would avoid DataOutputStream in this circumstance, you don't need its special processing. 

Please use plain text.
Contributor
bb_eibl
Posts: 26
Registered: ‎04-09-2013
My Device: not specified
My Carrier: not speciefied

Re: httpConnection can´t send query, difficulties with setRequestProperty

Thank´s, I appreciate your reply. I tried your suggestion (avoiding DataOutputStream using OutputStream instead), however, nothing changed as I see it. The content-length (param 11)  is still null.

I could not use getResponseMessage() as suggested since the server is already in the connected state when I send the dos.write.

 

This is a listing of the debugger in Eclipse.

 

I insert the code, which now also shows the section with DataInputStream.

If I am using "POST" as method the program will run in a loop and no input will be received.

Switching to "GET" instead, as shown below  will give the content of the page as input but not  the parameters asked for in the query String.

 

My questions: The server might not be able to run the http protocol should I change to udp which is specified for the server ?? Do you have any suggestion if this might help and what the difference between http and udp is. How can I find out which protocol is compatible wit hthe server ? As I understood it UDP is more rudimentary and supports less features as compared to http. Is there any site to get more information when to switch from http to udp.

 

 

 

byte b[] =new byte[2000];
                    long len = 0;
                    try {
                    	OutputStream dos =  httpConn.openOutputStream();
                        byte postdata [];
                        postdata=query.getBytes();
                        int i=postdata.length; 
                        httpConn.setRequestProperty("Content-Length","8");
                        String param12=String.valueOf(i);
                        String param11=httpConn.getRequestProperty("Content-Length");
                        String param13=httpConn.getRequestProperty("Content-Type");
                        String param14=httpConn.getRequestProperty("Connection");
                        httpConn.setRequestMethod(HttpConnection.GET);
                        
                         
                          dos.write(postdata,0,postdata.length);
                          
                         //String param15= httpConn.getResponseMessage();
                         dos.flush();
                         dos.close();
                         
                    
                         DataInputStream dis=null;
                          dis= httpConn.openDataInputStream();
                          
                          
                       
                          len = httpConn.getLength();
                                                       
                         dis.read(b,0,2000);     
                        
                         //dis.read(b,0,1000);
                         StringBuffer raw=new StringBuffer(new String(b,"utf-8"));
                         query=b.toString();
                                
                      
                          dis.close();

 Still desperate :smileymad:

Please use plain text.
Developer
peter_strange
Posts: 19,598
Registered: ‎07-14-2008
My Device: Not Specified

Re: httpConnection can´t send query, difficulties with setRequestProperty

[ Edited ]

Personally I have never tried setting a request Header and then attempting to get it - in fact I can see no reason for doing this and I suspect that it could screw things up.  The way I understand the http protocol, is that the request headers get formatted into the stream of bytes that are sent, along with the data, and then that gets interpreted by the Server.  The Server will use getRequestheader to find out what you sent.  The BB end should just send it.  So I guess the first question is why are you attempting to check this?  Or more importantly, can your server find these headers as it needs to? 

 

In addition, I suggest you actually set the content type.  I recommend the use of the HttpProtocolConstants class when setting all this - then you can be sure you are setting the correct attribute or value. 

 

If you are using standard http, then this statement is not correct:

"since the server is already in the connected state when I send the dos.write"

An http request is a single shot - you get one shot at sending data to the server, then it gets one shot at sending data back.  So with an http communication you are either sending data or receiving data.  You can't send some data, then receive some, then send some more.  If you want to do that, then look at a socket connection - in which case you will not be using http protocols. 

 

As noted, http is a single send, followed by a single receive.  On the Blackberry, the send is not actually initiated until the application program indicates it needs a response.  If you are using http communication then this should be by using getResponseCode().  Every http response has a code, and unless this indicates a good return code, then there is no value is trying to read the data from the connection - you will get garbage if anything.  So your code should follow a pattern like this:

 

open connection

set request headers

write POST data

get response

if response OK {

read data

}

close connection

 

Anyway, as you have noted, you need to make a decisions regarding the protocol to use.  Personally I would use http since this is well known and trusted and you will find other people who use it.  I also write socket connection code for BB's, that is more complicated.  I don't know UDP. 

 

In terms of learning http, UDP etc. this is not the right forum, but I can't tell what one is.  I personally find wikipedia useful and there are many places that discuss all the aspects of this on the web if you search.

 

Good luck. 

 

 

Please use plain text.
Contributor
bb_eibl
Posts: 26
Registered: ‎04-09-2013
My Device: not specified
My Carrier: not speciefied

Re: httpConnection can´t send query, difficulties with setRequestProperty

Thank´s  a lot for this very helpful and detailed answer. I found the complete list of HttpProtocolConstants through it, great. It will take me some time to verify your suggestions. I will report. set and get interplay is useful for me to check that I control/manage the server correctly.  almost  :smileyhappy:

Please use plain text.
Contributor
bb_eibl
Posts: 26
Registered: ‎04-09-2013
My Device: not specified
My Carrier: not speciefied

Re: httpConnection can´t send query, difficulties with setRequestProperty

Still I am doing things wrong !

As you suggested I inserted: param15= httpConn.getResponseCode();

 

however, then the programm runs in an endless loop when it reaches the dos.write();

 

If I remove the httpConn.getResponseCode(); statement then the program gets through, to the next breakpoint. But I don´t think it really posts the string. I experienced this earlier that after the dos.write I cannot use the getResponse() any longer the program will run in a loop. I thought it was because the dos. write puts the connection into a connected state and then the command get Resonse can no longer b  transmitted. You said, however, that this was wrong. Could you please clarif on this. My code, I include now also the set commands which I am using

 httpConn.setRequestProperty("Content-Type","text/html");
                    httpConn.setRequestProperty("Connection","keep-alive");
                 
                    
                    //************************************
                  String query="$M1value";
                
                	String charset="iso-8859-1";
                
                	
                    byte b[] =new byte[2000];
                    long len = 0;
                    try {
                    	OutputStream dos =  httpConn.openOutputStream();
                        byte postdata [];
                        postdata=query.getBytes();
                        int i=postdata.length; 
                        httpConn.setRequestProperty("Content-Length","8");
                        String param12=String.valueOf(i);
                        String param11=httpConn.getRequestProperty("Content-Length");
                        String param13=httpConn.getRequestProperty("Content-Type");
                        String param14=httpConn.getRequestProperty("Connection");
                        httpConn.setRequestMethod(HttpConnection.POST);
                        
                         
                          dos.write(postdata,0,postdata.length);
                          
                         //int param15= httpConn.getResponseCode();
                         dos.flush();
                         dos.close();
                         
                    
                         DataInputStream dis=null;
                          dis= httpConn.openDataInputStream();
                          
                          
                       
                          len = httpConn.getLength();
                                                       
                         dis.read(b,0,2000);     
                        
                         //dis.read(b,0,1000);
                         StringBuffer raw=new StringBuffer(new String(b,"utf-8"));
                         query=b.toString();
                                
                      
                          dis.close();

 desperate again :smileymad:

:

 

 

 

 

Please use plain text.
Developer
peter_strange
Posts: 19,598
Registered: ‎07-14-2008
My Device: Not Specified

Re: httpConnection can´t send query, difficulties with setRequestProperty

Suggested code:

 

                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postdata.length); // set length
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.....); // set type
                        httpConn.setRequestMethod(HttpConnection.POST);
                     OutputStream dos =  httpConn.openOutputStream();
                        byte postdata [] = query.getBytes();
                        dos.write(postdata,0,postdata.length);
                        dos.flush();
                        dos.close();                         
                        int rc = httpConn.getResponseCode();
                        if ( rc == HttpConnection.HTTP_OK ) {
                          DataInputStream dis=null;
                          dis= httpConn.openDataInputStream();
                          len = httpConn.getLength(); // Some servers don't set this                          
                          dis.read(b,0,2000);  // Where does b come from?  
                          StringBuffer raw=new StringBuffer(new String(b,"utf-8"));
                          query=b.toString();
                          dis.close();
                        } ....

 

debug this and tell us what happens. 

 

You say:

"then the programm runs in an endless loop when it reaches the dos.write();"

I'm going to say that is impossible.  I think it is more likely this throws an exception and goes to your exception handling.  But try it with the code above and tell us what happens.  And watch your catch to see if it gets invoked. 

Please use plain text.
Contributor
bb_eibl
Posts: 26
Registered: ‎04-09-2013
My Device: not specified
My Carrier: not speciefied

Re: httpConnection can´t send query, difficulties with setRequestProperty

I tried out your suggested code: Sorry to say this: nothing different happened the program gets stuck when performing the dos.write(postdata..)  statement as before. It does not reach dos.flush() and dos.close()

It idles in a loop and then goes to the catch (Exception e)  statement and prints "Error while closing" as you assumed. This appears in the bb output console.

 

I display the code:

 String query="$M1value";
                
                	String charset="iso-8859-1";
                
                	
                    byte b[] =new byte[2000];
                    long len = 0;
                    try {
                    	
                        byte postdata [];
                        postdata=query.getBytes();
                        int i=postdata.length; 
                      
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postdata.length));
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,"text/html");
                        httpConn.setRequestMethod(HttpConnection.POST);
                        OutputStream dos =  httpConn.openOutputStream();
                         
                          dos.write(postdata,0,postdata.length);
                          
                        
                         dos.flush();
                         dos.close();
                         int param15= httpConn.getResponseCode();
                         if(param15==HttpConnection.HTTP_OK) {
                        	 
                       
                    
                         DataInputStream dis=null;
                          dis= httpConn.openDataInputStream();
                          
                          
                       
                          len = httpConn.getLength();
                                                       
                         dis.read(b,0,2000);     
                        
                         //dis.read(b,0,1000);
                         StringBuffer raw=new StringBuffer(new String(b,"utf-8"));
                         query=b.toString();
                                
                      
                          dis.close();
                         }
                         
                          // status = httpConn.getResponseCode();
                          
                 
                              
                      } catch (Exception e) {
                           System.out.println("Error while closing: "  + e.getMessage());
                      }
                      System.out.println(b.toString());
                    

 I also display the BB simulator output console may be it helps. The last lines I can understand it shows the errorr and the displayed value b of the cath sequence.

[65.187] UIE: TD1(487, 331)
[65.187] UIE: TD2(-1, -1)
[65.304] AM: UI-TS: UP   0(487, 331) OSTS:65304
[65.304] UIE: GTapCount(1)
[65.312] AM: Starting HTTPDemo
[65.312] AM: Started HTTPDemo(325)
[65.312] UIE: TU1(487, 331)
[65.312] UIE: TU2(-1, -1)
[65.312] AM: Foreground is set: HTTPDemo(325)
[65.359] FocusHistory: Focus lost; App net_rim_bb_ribbon_app; Component net.rim.device.apps.internal.ribbon.l[65.359] auncher.ApplicationAreaGridField
[65.359] FocusHistory: Focus gained; App HTTPDemo; Component net.rim.device.api.ui.component.EditField
[65.359] TID:unable to execute in the app com.rim.samples.device.httpdemo.HTTPDemo@26a26760|java.lang.Object@[65.359] 952b331b|-1
[65.359] TID:IC-Swich en_GB 1364669241 1364669241 false
[65.367] GS(createSurface): Temporarily promoting window size
[65.367] VBW:0x1816e000:DD:0x37280000.
[65.367] SyncDec:StrImagepng (0,0)480x56->(0,0)480x56
[65.367] SyncDec:Done
[65.648] ASGE:e=0x29c9101386d412e3,t=289,n=25,a=11,q=0,g=0,p=net_rim_bb_ribbon_app(143)
[65.648] ASGE:e=0x29c9101386d412e3,t=289,n=99,a=2,q=1,g=0,p=net_rim_services_impl(11)
[65.648] BRM:IDL+
[65.648] BRM:SR+
[65.648] BRM:NMC:8663040
[65.648] BRM:JFR:23885704
[65.656] BRM:SR-
[65.656] BRM:NMC:8663040
[65.656] BRM:JFR:23885704
[65.664] BRM:IDL-
[66.718] THRTL: Out: 0 bytes
[66.726] THRTL: In: 0 bytes
[73.82] AM: Exit net_rim_bb_datatags(291)
[73.828] Process net_rim_bb_datatags(291) cleanup started
[73.828] Process net_rim_bb_datatags(291) cleanup done
[73.828] VM:EVTOv=7680,w=79
[73.828] 04/11 04:49:21.040 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformM[73.828] anagerImpl$3@a75080fd
[73.843] 04/11 04:49:21.055 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformM[73.843] anagerImpl$3@a75080fd
[88.296] No stack trace
[88.296] VM:PISVt=0,h=5314,id=d15a33128dfbb5d9
[88.296] VM:LNTDa=commit,t=0,p=net_rim_bb_voice_api,h=152
[113.765] THRTL: Out: 0 bytes
[113.765] THRTL: In: 0 bytes
[113.765] SmplT: stThu Apr 11 04:50:01 GMT 2013
[113.773] VM:PISVt=0,h=5314,id=d15a33128dfbb5d9
[113.773] VM:LNTDa=commit,t=0,p=net_rim_services_impl,h=113
[113.781] 04/11 04:50:01.178 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.filetransfer.BBMFileT[113.781] ransferManager@5af3e3a4
[113.789] Media:a:TmbF:2
[113.835] 04/11 04:50:01.241 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.filetransfer.BBMFileT[113.835] ransferManager@5af3e3a4
[150.39] BbiAuth:ERR:net.rim.device.api.crypto.bbiauth.BbiAuthException: No BBAuth service record configured
[173.187] THRTL: Out: 0 bytes
[173.187] THRTL: In: 0 bytes
[184.445] Model is not dirty.
[184.445] Completing PersistAndPurgeTask.doRequest() at: Thu Apr 11 04:51:12 GMT 2013
[188.578] Error while closing: null
[188.578] [B@867b3bc8

 

 

 

Still desperate :smileymad:

Please use plain text.
Developer
peter_strange
Posts: 19,598
Registered: ‎07-14-2008
My Device: Not Specified

Re: httpConnection can´t send query, difficulties with setRequestProperty

This is unusal.  Amongst things I don't understand is how it can possibly have a null message in the catch. 

 

I'd like to add some debugging.  First add this line to your catch:

 

System.out.println("Exception: "  + e.toString());

 

Add these lines at the start of your try:

 

System.out.println("Protocol: " + httpConn.getProtocol());

System.out.println("URL: " + httpConn.getUrl());

 

Let us know what you see. 

Please use plain text.