尝试将java(blackberry项目)连接到webservice时,.getResponseCode()挂起

时间:2011-06-10 12:47:42

标签: java blackberry blackberry-eclipse-plugin httpconnection

我正在尝试从eclipse中的blackberry项目连接到web服务。我的URLConnector代码如下

import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.ui.component.Dialog;


public class URLConnector 
{
HttpConnection con = null; 
InputStream is = null; 

public URLConnector()   {
    try 
    {
    Dialog.inform("1"); 
    String url = new String("https://webserviceBlahBlah");

    Dialog.inform(con.toString()); 
        int responseCode = con.getResponseCode(); 
        Dialog.inform("3"); 
        if (responseCode != HttpConnection.HTTP_OK) { 
            Dialog.inform("3.5"); 
            System.out.println(responseCode); 
        } 
        is = con.openInputStream(); 
        byte[] responseData = new byte[10000]; 
        int length = 0; 
        Dialog.inform("4"); 
        StringBuffer rawResponse = new StringBuffer(); 
        while (-1 != (length = is.read(responseData))) { 
            Dialog.inform("5"); 
            rawResponse.append(new String(responseData, 0, length)); 
        } 
        final String result = rawResponse.toString(); 
        System.out.println(result); 
        Dialog.inform("6"); 
    } 
    catch (Exception ex) 
    { 
        Dialog.inform("ex.getMessage()"); 
        System.out.println(ex.getMessage()); 
    } 
    finally 
    { 
        try { 
            is.close(); 
            is = null; 
            con.close(); 
            con = null; 
            Dialog.inform("8"); 
        } 
        catch(Exception e){
            Dialog.inform("e"); 
        } 
    } 
}

应用程序挂起con.getReponse()调用。它运行在黑莓9800模拟器上。任何帮助都会受到超级赞赏,因为我很困难

3 个答案:

答案 0 :(得分:2)

getResponseCode()不应该导致它被卡住,因为它只是读取它在建立连接后得到的响应。我的猜测实际上是悬挂的连接尝试。如果您正在开发5.0或更高版本,请查看ConnectionFactory类以确保正确创建连接。

答案 1 :(得分:0)

詹姆斯,我假设你打开MDS模拟器后,你发现你也遇到了问题,因为你从未打开连接?

无论如何只是为了给出最终的解决方案:

    HttpConnection con = null;
    InputStream is = null;
    try {
        System.out.println("1");
        String url = new String("http://myserver.com/index.html");

        //I added these two lines to your code and tested it with my own server and got a 200 RC.
        net.rim.device.api.io.transport.ConnectionFactory cf = new net.rim.device.api.io.transport.ConnectionFactory();
        con = (HttpConnection)cf.getConnection(url).getConnection();

        System.out.println(con.toString());
        int responseCode = con.getResponseCode();
        System.out.println("3 responseCode = " + responseCode);
        if (responseCode != HttpConnection.HTTP_OK) {
            System.out.println("3.5");
            System.out.println(responseCode);
        }

此外,如果您必须支持BBJava 5.0减号,您可以查看:http://www.versatilemonkey.com/HttpConnectionFactory.java。它不是完美的,但它是开始为5.0之前的平台创建连接的好地方。

答案 2 :(得分:0)

也许尝试在URL的最后添加; deviceside = true?帮助我。