我想调用一个url,并从我的黑莓应用程序的URL获取响应数据。为此,我使用HttpConnection
。这里是我使用的代码:在黑莓HttpConnection概要在模拟器中运行
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Dialog;
import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;
import javax.microedition.io.HttpConnection;
import java.io.DataInputStream;
import java.io.IOException;
public class TestApp extends UiApplication {
private MainScreen _mainScreen;
private static TestApp _app;
public TestApp(){
_mainScreen = new MainScreen();
LabelField testField = new LabelField("hello world");
_mainScreen.add(testField);
pushScreen(_mainScreen);
HttpConnection c = null;
DataInputStream dis = null;
try {
System.out.println("0");
c = (HttpConnection)Connector.open("http://www.google.com");
System.out.println("1");
int rc = c.getResponseCode();
System.out.println("2");
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
System.out.println("3");
dis = c.openDataInputStream();
System.out.println("4");
int len = (int)c.getLength();
if (len > 0) {
byte[] data = new byte[len];
dis.readFully(data);
} else {
int ch;
while ((ch = dis.read()) != -1) {
//...
}
}
} catch(Exception e){
e.printStackTrace();
}finally {
try {
if (dis != null)
dis.close();
if (c != null)
c.close();
} catch (IOException e) {
e.printStackTrace();
}
catch(NullPointerException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
_app = new TestApp();
_app.enterEventDispatcher();
}
}
当我尝试运行模拟器的代码,我得到“0”,那么“1”之后,经过很长一段时间“没有堆栈跟踪”是一个出现调试窗口,只要文本出现,带有文本的关卡应用程序就会在模拟器屏幕中可见。在模拟器的互联网连接中没有问题,我已经设置了Wi-Fi,并且我已经测试过可以在浏览器中打开任何网站。我的代码中有什么问题?
你真的应该(不,也许)在一个单独的线程上运行http获取。你所做的是让事件线程(因此OS)阻塞等待getResponseCode()返回。自从您阻止操作系统后,它可能永远不会执行此操作。 – Richard 2012-02-07 17:30:22