Blackberry发送HTTPPost请求

时间:2011-02-15 15:30:23

标签: blackberry

我正在为黑莓开发和应用程序,我需要向我的服务器发送一个Http Post Request。我正在使用模拟器来测试我的应用程序,我发现此代码以发送请求:

http://vasudevkamath.techfiz.com/general/posting-data-via-http-from-blackberry/

但我无法让它发挥作用,因为它在这一行中失败了:

int rc = _httpConnection.getResponseCode();

有什么想法吗?

感谢

5 个答案:

答案 0 :(得分:2)

以下是有关如何发送POST请求的示例代码:

HttpConnection c = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
c.setRequestMethod(HttpConnection.POST);
OutputStream os = c.openOutputStream();
os.write(request.getBytes("UTF-8"));
os.flush();
os.close();
InputStream is = c.openInputStream();

请确保在单独的帖子中使用此代码。

答案 1 :(得分:2)

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"; // If you are using WiFi
        //String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
        //String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP

        if(DeviceInfo.isSimulator()) // if you are using simulator
            formattedURL = absoluteURL;

        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;
}

答案 2 :(得分:1)

我知道这个问题已经很老了,OP现在可能解决了这个问题,但我遇到了同样的问题,并设法解决了这个问题!

您需要将;deviceside=true附加到您的网址。

例如,您的网址将从"http://example.com/directory/submitpost.php"更改为"http://example.com/directory/submitpost.php;deviceside=true"

我在这里找到了这个:http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-make-an-HTTP-or-socket-connection/ta-p/445879

我的POST请求在3分钟后超时(我看到My Comment),但是它会附加到网址上。

我还建议使用ConnectionFactory。这是我的一些代码:

Network.httpPost("http://example.com/directory/submitpost.php;deviceside=true", paramNamesArray, paramValsArray)
public static void httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {
        ConnectionFactory conFactory = new ConnectionFactory();
        conFactory.setTimeLimit(1000);
        HttpConnection conn = (HttpConnection) conFactory.getConnection(urlStr).getConnection();
        conn.setRequestMethod(HttpConnection.POST);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < paramName.length; i++) {
            sb.append(paramName[i]);
            sb.append("=");
            sb.append(paramVal[i]);
            sb.append("&");
        }
        byte[] postData = sb.toString().getBytes("UTF-8");
        conn.setRequestProperty("Content-Length",new Integer(postData.length).toString());

        OutputStream out = conn.openOutputStream();
        out.write(postData);
        //out.flush();      //Throws an Exception for some reason/Doesn't do anything anyways
        out.close();

        //This writes to our connection and waits for a response 
        if (conn.getResponseCode() != 200) {
            throw new Exception(conn.getResponseMessage());
        }
}

答案 3 :(得分:0)

不确定您发布的网站,但我已成功使用黑莓网站上提供的示例ConnectionFactory代码。

http://supportforums.blackberry.com/t5/Java-Development/Sample-Code-Using-the-ConnectionFactory-class-in-a-BrowserField/ta-p/532860

请确保不要在EventThread上调用连接。

答案 4 :(得分:0)

这就是你添加参数的方法,完整答案就在这里:

StringBuffer postData = new StringBuffer();

                    httpConn = (HttpConnection) Connector.open("https://surveys2.kenexa.com/feedbacksurveyapi/login?");
                    httpConn.setRequestMethod(HttpConnection.POST);

                    postData.append("username="+username);
                    postData.append("&password="+pass);
                    postData.append("&projectcode="+projectid);
                    String encodedData = postData.toString();

                    httpConn.setRequestProperty("Content-Language", "en-US");
                    httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                    httpConn.setRequestProperty("Content-Length",(new Integer(encodedData.length())).toString());
                    byte[] postDataByte = postData.toString().getBytes("UTF-8");

                    OutputStream out = httpConn.openOutputStream(); 
                    out.write(postDataByte);
                    out.close();

                    httpConn.getResponseCode();