【问题标题】:Blackberry send a HTTPPost request黑莓发送 HTTPPost 请求
【发布时间】:2011-02-15 15:30:22
【问题描述】:

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

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

但我无法让它工作,因为它在这一行失败:

int rc = _httpConnection.getResponseCode();

有什么想法吗?

谢谢

【问题讨论】:

  • 您遇到的错误是什么?这条线会发生什么?
  • 是的,发生了什么事?另外,您是在事件线程上调用 postData() 方法,还是启动一个单独的线程?事件线程上的 HTTP 访问会导致问题。
  • 也遇到了这个问题。线程(不是 UI)在httpConn.getResponseCode(); 等待一段时间,然后以异常退出:java.io.InterruptedIOException: Local connection timed out after ~ 120000。可以从模拟器上的浏览器访问服务器。我正在使用类似于以下答案的代码。 @xger86x 你搞定这个了吗?

标签: blackberry


【解决方案1】:

这是一个关于如何发送 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();

请确保您在单独的线程中使用此代码。

【讨论】:

  • 如何设置POST参数?
【解决方案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;
}

【讨论】:

  • 请务必在单独的线程中调用此方法,并且在更新 UI 之前,您必须使用 Application.getUiApplication.getEventLock(); 获取 eventLock;
【解决方案3】:

我知道这个问题已经很老了,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),但是将它附加到 url 后它可以正常工作。

我还建议使用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());
        }
}

【讨论】:

    【解决方案4】:

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

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

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

    【讨论】:

      【解决方案5】:

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

      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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-23
        相关资源
        最近更新 更多