使用以下代码,服务器受到攻击,但我也想在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());
}
答案 0 :(得分:2)
您滥用ConnectionFactory.getConnection(String url, int transportType, String ConnectionUID)
方法。例如,检查您传递的内容为transportType
...
以下是关于返回值的API:
返回:如果可以建立连接,则返回ConnectionDescriptor; 否则为null
所以,它只是失败并返回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 ..
答案 1 :(得分:1)
查看链接的答案并验证“登录”程序的实施是否适合您的需求: authentication username password url in blackberry