Monday, October 31, 2011

HTTP post method in Blackberry


public void post()
{
URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
//passing q’s value and ie’s value
postData.append("UserName","your username");
postData.append("Password", "your password");

ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try{
conDesc = conFactory.getConnection("https://www.pmamsmartselect.com/PMAMSS-Webservices/MobileService.asmx/LoginCheck;deviceside=true");
}catch(Exception e){
System.out.println(e.toString()+":"+e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if(null != conDesc){
try{
HttpConnection connection = (HttpConnection)conDesc.getConnection();
//set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length", Integer.toString(postData.size())); //body content of post data
connection.setRequestProperty("Connection", "close"); // close the connection after success sending request and receiving response from the server
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // we set the content of this request as application/x-www-form-urlencoded, because the post data is encoded as form-urlencoded(if you print the post data string, it will be like this -> q=remoQte&ie=UTF-8).

//now it is time to write the post data into OutputStream
OutputStream out = connection.openOutputStream();
out.write(postData.getBytes());
out.flush();
out.close();

int responseCode = connection.getResponseCode(); //when this code is called, the post data request will be send to server, and after that we can read the response from the server if the response code is 200 (HTTP OK).
if(responseCode == HttpConnection.HTTP_OK){
//read the response from the server, if the response is ascii character, you can use this following code, otherwise, you must use array of byte instead of String
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while((read = in.read())!= -1)
buf.append((char)read);
response = buf.toString();
}
Dialog.inform(response);
//don’t forget to close the connection
connection.close();

}catch(Exception e){
System.out.println(e.toString()+":"+e.getMessage());
}
}
}

1 comment: