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
New Developer
ffcolor
Posts: 9
Registered: ‎09-30-2009
My Device: Not Specified
Accepted Solution

HttpConnection set to POST does not work

Hi

 

I am trying to connect from my BB to a php site with POST method. the application is started and I can sniff the traffic on my network interface. But with the following code I always have the "GET" method and my PHP script cannot work.

 

the code:

 

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HttpTest1 extends MIDlet {

   private Display display;

    public HttpTest1() {
    try {
 
          getBirthdayFromNameUsingPost("7788");
    }
    catch (IOException e) {
        System.out.println("IOException " + e.toString());
    }
  }

    /**
     * MIDlet lifecycle functions
     */
    public void startApp() { }

    public void pauseApp() {

    }

    public void destroyApp(boolean unconditional) {
    }

 

  /**
      This function connects to web server and passes the parameter name to the
    target in HTTP POST request. Upon successful connection, web server returns
    birthday for 'name'.
    This function also calls getConnectionInformation to retrieve properties of
    HTTPConnection
   **/

  public void getBirthdayFromNameUsingPost(String name) throws IOException {

    HttpConnection httpConn = null;
      String url = "http://mysite.php;deviceside=true";
    InputStream is = null;
    OutputStream os = null;

    try {
        os = httpConn.openOutputStream();
      // Open an HTTP Connection object
      httpConn = (HttpConnection)Connector.open(url);
      // Setup HTTP Request to POST
      httpConn.setRequestMethod(HttpConnection.POST);

      httpConn.setRequestProperty("User-Agent", "BlackBerry");
     // httpConn.setRequestProperty("Accept_Language","en-US");
      //Content-Type is must to pass parameters in POST Request
      httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      // This function retrieves the information of this connection
     // getConnectionInformation(httpConn);


     

      String params;
      params = "name=" + name;

      os.write(params.getBytes());

      /**Caution: os.flush() is controversial. It may create unexpected behavior
            on certain mobile devices. Try it out for your mobile device **/

      //os.flush();

      // Read Response from the Server

      StringBuffer sb = new StringBuffer();
      is = httpConn.openDataInputStream();
      int chr;
      while ((chr = is.read()) != -1)
        sb.append((char) chr);

      // Web Server just returns the birthday in mm/dd/yy format.
      System.out.println(name+"'s Birthday is " + sb.toString());

      } finally {
        if(is!= null)
           is.close();
          if(os != null)
            os.close();
      if(httpConn != null)
            httpConn.close();
    }

    }


    /***  After setup, attributes of the HttpConnection object can be retrived using
        various get methods.
    ***/


}

 

 

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

Re: HttpConnection set to POST does not work

I think that you should be using URLEncodedPostData for your post data.

 

Something like this:

 

URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, true); postData.append("name",name);

 

Please use plain text.
New Developer
ffcolor
Posts: 9
Registered: ‎09-30-2009
My Device: Not Specified

Re: HttpConnection set to POST does not work

Hi,

 

Maybe you are right, but I dont want to spend any money for signing code, because of using encoding.

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

Re: HttpConnection set to POST does not work

Saving $20!  Hm...

 

Anyway, this code might help the encoding:

 

// Unreserved punctuation mark/symbols private static String mark = "-_.!~*'()\""; /** * Converts Hex digit to a UTF-8 "Hex" character * @param digitValue digit to convert to Hex * @return the converted Hex digit */ static private char toHexChar(int digitValue) { if (digitValue < 10) // Convert value 0-9 to char 0-9 hex char return (char)('0' + digitValue); else // Convert value 10-15 to A-F hex char return (char)('A' + (digitValue - 10)); } /** * Encodes a URL - This method assumes UTF-8 * @param url URL to encode * @return the encoded URL */ static public String encodeURL(String url) { StringBuffer encodedUrl = new StringBuffer(); // Encoded URL int len = url.length(); // Encode each URL character for(int i = 0; i < len; i++) { char c = url.charAt(i); // Get next character if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) // Alphanumeric characters require no encoding, append as is encodedUrl.append(c); else { int imark = mark.indexOf(c); if (imark >=0) { // Unreserved punctuation marks and symbols require // no encoding, append as is encodedUrl.append(c); } else { // Encode all other characters to Hex, using the format "%XX", // where XX are the hex digits encodedUrl.append('%'); // Add % character // Encode the character's high-order nibble to Hex encodedUrl.append(toHexChar((c & 0xF0) >> 4)); // Encode the character's low-order nibble to Hex encodedUrl.append(toHexChar (c & 0x0F)); } } } return encodedUrl.toString(); // Return encoded URL }

 

Please use plain text.
New Developer
ffcolor
Posts: 9
Registered: ‎09-30-2009
My Device: Not Specified

Re: HttpConnection set to POST does not work

Ok, what about the code I found. Why I cannot get the POST method working?
Please use plain text.
Developer
peter_strange
Posts: 19,609
Registered: ‎07-14-2008
My Device: Not Specified

Re: HttpConnection set to POST does not work

Try changing

 

      os.write(params.getBytes()); 

 

to:

 

      bytes postBytes = params.getBytes();
      c.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
      os.write(postBytes);
      os.flush();

Please use plain text.
New Developer
ffcolor
Posts: 9
Registered: ‎09-30-2009
My Device: Not Specified

Re: HttpConnection set to POST does not work

hi,

 

If you mean:

 

  byte [] postBytes = params.getBytes();
      httpConn.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
      os.write(postBytes);
      os.flush();

 

it does not make any difference.

Please use plain text.
Developer
SergGr
Posts: 166
Registered: ‎05-07-2009
My Device: Not Specified

Re: HttpConnection set to POST does not work

The code you provided in your first post looks suspicious. Could you provide some working example? The thing why this code can't work is that initialization of os should fail.

 

HttpConnection httpConn = null; //some code OutputStream os = null; try { os = httpConn.openOutputStream(); // Open an HTTP Connection object httpConn = (HttpConnection)Connector.open(url); //some more code

According to the snippet you are calling openOpenStream on null!

Proper code i.e. with stream opened for real connection works on my computer as I would expect.The only idea I have is that httpConn is not a local variable of the method but class member and so you open stream on old connection and then create new one. If this is not the case, could you provide more real code snippet that doesn't work on your computer?

 

 

 


--------------------------------------------------------------------------------------------------------
If your issue is solved, set "Solution" mark at the relevant post.
Don't hesitate to Kudos people whose posts helped you.
Please use plain text.
Developer
ydaraishy
Posts: 562
Registered: ‎09-30-2009
My Device: Not Specified

Re: HttpConnection set to POST does not work

[ Edited ]

After taking SergGr's advice and moving that line down, try Connector.open(url, Connector.READ_WRITE).

 

Message Edited by ydaraishy on 09-30-2009 06:36 PM
Please use plain text.
New Developer
ffcolor
Posts: 9
Registered: ‎09-30-2009
My Device: Not Specified

Re: HttpConnection set to POST does not work

The code now looks like this (the part for making http connection):

 

  try {
      
      httpConn = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
      httpConn.setRequestMethod(HttpConnection.POST);
      httpConn.setRequestProperty("User-Agent", "BlackBerry");
      httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      String params;
      params = "name=" + name;
     // os.write(params.getBytes());
      byte [] postBytes = params.getBytes();
      httpConn.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
       os = httpConn.openOutputStream();
      os.write(postBytes);
      os.flush();

 

but wireshark (network sniffer) still see packet: GET /test.php HTTP/1.1 instead of POST - so the remote script will never fetch the data I am trying to send. the problem with this is that it still set somehow as GET method instead of POST.

Please use plain text.