0

使用以下代码,服务器受到攻击,但我也想在 POST 方法中发送变量。

但它只是给了我一个空指针异常。它与OutputStream. 我已经检查过postData......它有一些地址,这意味着它不为空。

那么为什么给我空指针异常呢?

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());
}
4

2 回答 2

2

您正在滥用该ConnectionFactory.getConnection(String url, int transportType, String ConnectionUID)方法。例如,检查您传递的内容transportType...

以下是 API 关于返回值的说明:

返回: 如果可以建立连接,则返回 ConnectionDescriptor;否则为空

所以,它只是失败并返回null。这就是你获得 NPE 的原因。

更新

我建议只使用更简单的 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 ..
于 2012-11-14T13:59:02.050 回答
1

查看链接的答案并验证“登录”程序的实现是否满足您的需求: authentication username password url in blackberry

于 2012-11-14T12:52:20.247 回答