Monday, March 25, 2013

Call HTTP Post method on Blackberry

As Continues work on Blackberry today i need to integrated http POST method on blackberry. If you want to implement POST method on Blackberry following code will very help full to you. Nothing you have to do anything just parse parameter one is Post URL. you can use URL as following format.

http://yourdomainname/webservicenamehere.php

public StringBuffer httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {
  
  StringBuffer bodyData = new StringBuffer(256);
  ConnectionFactory conFactory = new ConnectionFactory();
  conFactory.setTimeLimit(1000);
  HttpConnection conn = (HttpConnection) conFactory.getConnection(urlStr)
    .getConnection();
  conn.setRequestMethod(HttpConnection.POST);
  conn.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");

  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < paramName.length; i++) {
   sb.append(paramName[i]);
   sb.append("=");
   sb.append(paramVal[i]);
   sb.append("&");
  }
  byte[] postData = sb.toString().getBytes("UTF-8");
  conn.setRequestProperty("Content-Length",
    new Integer(postData.length).toString());

  OutputStream out = conn.openOutputStream();
  out.write(postData);
  out.close();

  // This writes to our connection and waits for a response
  if (conn.getResponseCode() != 200) {
   throw new Exception(conn.getResponseMessage());
  }
  InputStream inputStream = conn.openInputStream();
  byte[] data = new byte[256];
  int len = 0;
  int size = 0;
  while (-1 != (len = inputStream.read(data))) {
   bodyData.append(new String(data, 0, len, "UTF-8"));
   size += len;
  }

  if (inputStream != null) {
   inputStream.close();
  }
  return bodyData;
 }
Hope it will help full. don't forget to write comment.

No comments:

Post a Comment