hi friends I am new to blackberry programming, I am getting problem while making HTTPConnection to send GET request to a php web service, following is the code I am trying,
HttpConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
String result = null;
String url = "http://localhost/blackberry/locations.php?device_id="+id+"&lat="+lat+"&lon="+lon
try{
conn = (HttpConnection) Connector.open(url,Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if(conn.getResponseCode() == HttpConnection.HTTP_OK){
in = conn.openInputStream();
int chr;
//xp.parse(in, handler);
while((chr = in.read()) != -1){
buff.append((char)chr);
}
result = buff.toString();
}
else{
result = "Error in connection";
return result;
}
} catch(Exception ex){
System.out.println(ex.getMessage());
} finally{
try {
in.close();
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
please suggest me solution, Thanks
Regard开发者_Go百科.
A few comments:
- If you are using OS 5.0+, use the network API instead. For more details, please see this answer
- You cannot connect to localhost from BlackBerry.
- Use IOUtilities.streamToBytes instead of that while loop to read the data to a byte array.
Sorry, my reputation does not allow me to comment. My guess is: you cannot connect to localhost, therefore the response code is different from HTTP_OK, therefore the input stream 'in' never gets opened and the variable 'in' is still null when the stream is about to be closed in the finally-block. Hence the NullPointerException.
Try to use if (in != null) in.close();
instead.
精彩评论