打开HTTP连接

时间:2011-02-21 15:48:28

标签: http blackberry httpwebrequest

我需要通过Blackberry上的无线互联网服务打开HTTP连接。例如:

(StreamConnection)Connector.open(“socket:// testserver:600;interface=wifi”);

任何人都可以向我提供有关如何执行此操作的信息吗?

2 个答案:

答案 0 :(得分:2)

您试用此BlackBerry知识库文章:
What Is - Different ways to make an HTTP or socket connection

答案 1 :(得分:0)

    public static ResponseBean sendRequestAndReceiveResponse(String method, String absoluteURL, String bodyData, boolean readResponseBody) 
    throws IOException
    {
        ResponseBean responseBean = new ResponseBean();
        HttpConnection httpConnection = null;

        try
        {

            String formattedURL = absoluteURL + "deviceside=true;interface=wifi";
            //String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
            //String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP

            httpConnection = (HttpConnection) Connector.open(formattedURL);

            httpConnection.setRequestMethod(method);

            if (bodyData != null && bodyData.length() > 0)
            {                               
                OutputStream os = httpConnection.openOutputStream();
                os.write(bodyData.getBytes("UTF-8"));
            }           

            int responseCode = httpConnection.getResponseCode();
            responseBean.setResponseCode(responseCode);

            if (readResponseBody)
            {
                responseBean.setBodyData(readBodyData(httpConnection));
            }
        }
        catch (IOException ex)
        {                       
            System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
            throw ex;
        }
        catch(Exception ex)
        {                       
            System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
            throw new IOException(ex.toString());
        }
        finally
        {
            if (httpConnection != null)
                httpConnection.close();
        }

        return responseBean;
    }

    public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException
    {   
        if(httpConnection == null)
            return null;

        StringBuffer bodyData = new StringBuffer(256);                          
        InputStream inputStream = httpConnection.openDataInputStream();

        byte[] data = new byte[256];
        int len = 0;
        int size = 0;

        while ( -1 != (len = inputStream.read(data)) )
        {
            bodyData.append(new String(data, 0, len,"UTF-8"));
            size += len;
        }

        if (inputStream != null)
        {
            inputStream.close();            
        }

        return bodyData;
    }