问题
With the following code, the server is getting hit, but I also want to send variables in POST method.
But it just gives me a null pointer exception. It has something to do with the OutputStream
. I have checked postData
... it has some address, which means it is not null.
So why I am given null pointer exception?
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
try {
connDesc = connFact.getConnection("http://example.com/login.php", Connector.READ_WRITE, returnContent);
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("count", "Hell Yeah!");
byte[] postData = encPostData.toString().getBytes("UTF-8");
httpConn.setRequestProperty("Content-length", String.valueOf(postData.length));
Dialog.alert("Post Data: " + postData);
OutputStream os = httpConn.openOutputStream();
os.write(postData);
os.flush();
httpConn = (HttpConnection) connDesc.getConnection();
final int iResponseCode = httpConn.getResponseCode();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
//Dialog.alert("Response code: " + Integer.toString(iResponseCode));
}
});
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
回答1:
You are misusing the ConnectionFactory.getConnection(String url, int transportType, String ConnectionUID)
method. For instance, check what you pass as transportType
...
Here is what API says about return value:
Returns: a ConnectionDescriptor if a connection can be established; null otherwise
So, it just fails and returns null
. And that's why you get a NPE.
UPDATE:
I would recommend to just use a simpler API ConnectionFactory.getConnection(String url)
:
ConnectionDescriptor cd = connFact.getConnection("http://example.com/login.php");
if (cd == null) {
// throw an error signalling there is no connectivity right now
}
HttpConnection httpConn = (HttpConnection) cd.getConnection();
// the rest of the code working with httpConn ..
回答2:
Have a look to the linked answer and verify if that implementation of 'login' procedure is ok for your needs: authentication username password url in blackberry
来源:https://stackoverflow.com/questions/13377021/blackberry-httppost-null-pointer-exception-java