黑莓发送HTTPPost请求

问题描述:

我正在开发和黑莓应用程序,我需要发送一个Http发送请求到我的服务器。我使用模拟器,以测试我的应用程序,我发现这个代码,以便发送请求:黑莓发送HTTPPost请求

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

但我不能得到它的工作,因为它在这一行失败:

int rc = _httpConnection.getResponseCode(); 

任何想法?

感谢

+2

什么是错误您收到?这条线会发生什么? – Tamar 2011-02-15 16:55:37

+0

是的,发生了什么事?另外,你是在事件线程上调用postData()方法,还是启动一个单独的线程?事件线程的HTTP访问会导致问题。 – Richard 2011-02-15 18:48:31

+0

也得到这个问题。线程(而不是UI)在`httpConn.getResponseCode();`等待一段时间然后退出异常:java.io.InterruptedIOException:本地连接在〜120000之后超时。服务器可以从模拟器上的浏览器访问。我使用的代码与下面的答案类似。 @ xger86x你认为这个出来了吗? – javajavajavajavajava 2012-08-09 14:45:55

这里是如何发送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(); 

只要确保你在一个单独的线程中使用此代码。

不知道你张贴的网站,但我已经成功地用于提供在黑莓网站上的样品连接工厂代码。

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

只要确保不来调用EventThread的连接。

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

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

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

因此,例如,您的网址将从"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()); 
     } 
} 

。这样你添加参数,全部答案就在这里:

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