Here is the code from client side:

public class TempMail {
	
	private String url = "http://localhost:9081/Servlet_Test/Servlet_Test";
	
	public StringBuffer invokeServletForLogin(String unm, int key1, int key2, 
			byte[] pwd, byte[] newPwd, String flag) throws IOException {
		HttpConnection c = null;
		InputStream is = null;
		OutputStream os = null;
		StringBuffer b = new StringBuffer();
		String msg=null;

		try {
			

		c=SetHttpConnection(c);
		os = c.openOutputStream();
		os=writeStr("type=login", os);
        os=writeStr("&username="+unm, os);
        os=writeStr("&key1="+key1, os);
        os=writeStr("&key2="+key2, os);
        
        if (pwd!=null){
        	os=writeStr("&password=", os);
            os=writeBytes(pwd, os);
        }
        if (newPwd!=null){
           os=writeStr("&newpassword=", os);
           os=writeBytes(newPwd, os);
        }
        os=writeStr("&loginflag="+flag, os);
		os.flush();
		is = c.openDataInputStream();
        b=readStr(is);
		} catch (Exception e)
		{
		e.printStackTrace();
		}
		finally
		{closeAll(is, os, c);
		}
		return b;
		}
	
	private HttpConnection SetHttpConnection(HttpConnection c){
		try{
		c = (HttpConnection) Connector.open(url);
		c.setRequestMethod(HttpConnection.POST);
		c.setRequestProperty("User-Agent", "Profile/MIDP-2.1 Configuration/CLDC-1.1");
		c.setRequestProperty("Content-Language", "en-CA");
		c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

		}catch (Exception e)
		{
			e.printStackTrace();
		}
		return c;
	}
	
	private OutputStream writeStr(String str, OutputStream os){
		try {
			if (str!=null){
	           byte postmsg[] = str.getBytes();
	           for (int i = 0; i < postmsg.length; i++)
	           {
	              os.write(postmsg[i]);
	           }
			}
		}catch (Exception e)
		{
			e.printStackTrace();
		}
		return os;
	}
	
	private OutputStream writeBytes(byte[] byteArray, OutputStream os){
		try {

	           for (int i = 0; i < byteArray.length; i++)
	           {
	              os.write(byteArray[i]);
	           }
			
		}catch (Exception e)
		{
			e.printStackTrace();
		}
		return os;
	}	
	
	private StringBuffer readStr(InputStream is){
		StringBuffer b=new StringBuffer();
		try{
		  int ch;
		  while ((ch = is.read()) != -1)
		  {
		    b.append((char) ch);
		   }
		 } catch (Exception e)
		   {
		     e.printStackTrace();
		    }
		return b;
	}
	
	private void closeAll(InputStream is, OutputStream os, HttpConnection c){
		try{
		if (is != null)  is.close();
		if (os != null) os.close();
		if (c != null) c.close();
	    }catch (Exception e)
		   {
		     e.printStackTrace();
		    }
	}

}

Here is the code from server side. Tried to read byte[] from servlet and always got request.getContentLength()=-1. So I just comment this part out.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		System.out.println("In DoPost()");
        //response.setContentType("text/plain");
        response.setContentType("multipart/form-data");
        
       	/*InputStream is = request.getInputStream();
		int len=request.getContentLength();
		System.out.println("len is "+len);
        byte[] ba = new byte[len];
        int len2 = is.read(ba);
        for (int i=0; i<len; i++)
        	System.out.println(ba[i]);
        
        is.close();
        */
        
        /*-----------------------Testing-----------------------------
        
        InputStream is = null;
        byte[] byteData = null;

        int contentLen = request.getContentLength(); // returns 13612
        
        System.out.println("len is "+contentLen);

        is = request.getInputStream();

        byteData = new byte[contentLen];

        int bytesRead = 0;
        int i = 0;
        while ( i < byteData.length ) 
        {
        // Note that all 13612 bytes are being read in one call to this read
        // on my machine.
        bytesRead = is.read(byteData, i, byteData.length - i);

        if ( bytesRead < 0 )
        {
        System.out.println("bytesRead<0..."); // end of stream reached early
        }

        i += bytesRead;
        }
        
        for (int ii=0; ii<contentLen; ii++ )
        	System.out.println(ii+". "+byteData[ii]);
        
      -----------------------End of Testing-----------------------------*/

        
        String type=null;
        Enumeration parameters = request.getParameterNames();
		while (parameters.hasMoreElements()){
			String param = (String)parameters.nextElement();
			if(param.equalsIgnoreCase("type"))
			{
				type=request.getParameter(param);
				System.out.println("type="+type);
				if (type.equals("login")) DoLogin(request, response);
			}
		}
        

	}
	
	private void DoLogin( HttpServletRequest request, HttpServletResponse response){
        String name=null;
        String password=null;
        String newpassword=null;
        String loginflag=null;
        int key1=0, key2=0;
        
        
        try {
        	
        	Enumeration parameters = request.getParameterNames();
		    while (parameters.hasMoreElements()){
			String param = (String)parameters.nextElement();
			
			if(param.equalsIgnoreCase("username"))
			{
				name=request.getParameter(param);
				System.out.println("Here it is:"+name);
			}
			if(param.equalsIgnoreCase("key1"))
			{
				key1=Integer.parseInt(request.getParameter(param));
				System.out.println("Here it is:"+key1);
			}
			if(param.equalsIgnoreCase("key2"))
			{
				key2=Integer.parseInt(request.getParameter(param));
				System.out.println("Here it is:"+key2);
			}
			if(param.equalsIgnoreCase("password"))
			{
				password=request.getParameter("password");
				System.out.println("Here it is:"+password);
				
				
			}
			if(param.equalsIgnoreCase("newpassword"))
			{
				newpassword=request.getParameter(param);
				System.out.println("Here it is:"+newpassword);
			}
			if(param.equalsIgnoreCase("loginflag"))
			{
				loginflag=request.getParameter(param);
				System.out.println("Here it is:"+loginflag);
			}
		}
		
		
        PrintWriter out = response.getWriter();
            out.println(name);
            out.println(key1);
            out.println(key2);
            out.println(password);
            out.println(newpassword);
            out.println(loginflag);
            out.print("Status: OKAY");
        out.close();
	} catch (Exception e){System.out.println(e.toString());}
	}

I was playing around with your code and so far did not found out why send string on server side once retrieved from request is coming out as null...

I can retrieve String but I cannot retrieve byte[] correctly. That's the problem. Is there some of my settings wrong? -Mydreamgirl

I see what you trying to do now! I are looking for secure way to forward credentials (username, password). For this you should use BouncyCastle library to encode it on client side and then send it to server side for decoding and further processing

I have sample somewhere of it if you want and can find it for you if you want it...

Peter,

I have done encryption for password and tried pass it to server side for descryption, which requires byte[]. I have already had my own encryption library and I do not need Bounce Casle Library, but I need to know how to read byte[] in server side. If you can provide me with soem sample code about that, that would be great!!!

Thanks a lot,
Mydreamgirl

Well what I was trying to say is that you cannot send byte array as sort of object that you can simply pick up from request through parameter request. You have to choose either work with parameters or have stream that is then transferred to a document(image, pdf or similar document upload). However you can run your freshly encoded data stored in byte array through simple method to turn byte array to hexadecimal string

if (pwd!=null){
        	os=writeStr("&password=", os);
            os=writeBytes(new String(HexCodec.bytesToHex(pwd)).getBytes(), os);
        }

with use of following simple class

public class HexCodec {
  private static final char[] kDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    'a', 'b', 'c', 'd', 'e', 'f'};

  public static char[] bytesToHex(byte[] raw) {
    int length = raw.length;
    char[] hex = new char[length * 2];
    for (int i = 0; i < length; i++) {
      int value = (raw[i] + 256) % 256;
      int highIndex = value >> 4;
      int lowIndex = value & 0x0f;
      hex[i * 2 + 0] = kDigits[highIndex];
      hex[i * 2 + 1] = kDigits[lowIndex];
    }
    return hex;
  }

  public static byte[] hexToBytes(char[] hex) {
    int length = hex.length / 2;
    byte[] raw = new byte[length];
    for (int i = 0; i < length; i++) {
      int high = Character.digit(hex[i * 2], 16);
      int low = Character.digit(hex[i * 2 + 1], 16);
      int value = (high << 4) | low;
      if (value > 127) value -= 256;
      raw[i] = (byte) value;
    }
    return raw;
  }
}

Then on the other end just ask for relevant parameter, get data, run it trough hexToBytes method to get bytes array, and then you can decode it

Peter,

Thank you so much for sahring it with me. Can you also provide me with sample code in server side? -Mydreamgirl

I got it. It looks like it is working. Thanks a lot. -Mydreamgirl

If everything is fine then please mark thread as solved. Thank you!

I got it. It looks like it is working. Thanks a lot. -Mydreamgirl

Hi,

Can you please share, how it started working... Actually i am also stuck with more or less the same issue here...

Thanks
Arun

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.