黑莓HTTP POST请求 [英] HTTP Post request on BlackBerry

查看:196
本文介绍了黑莓HTTP POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送一个JSON字符串,从我的黑莓OS< 7.X应用到我的服务器。我想使用一个HTTP POST请求。什么到目前为止,我所做的是:

 字符串httpURL =HTTP://ip_of_my_server/phpServer/receiver2.php/+ jsonString;尝试{
    HttpConnection的httpConn;
    httpConn =(的HttpConnection)Connector.open(httpURL + getConnectionString());
    httpConn.setRequestMethod(HttpConnection.POST);
    httpConn.setRequestProperty(内容类型,应用/ JSON的;字符集= UTF-8);
    DataOutputStream类_outStream =新的DataOutputStream类(httpConn.openDataOutputStream());
    字节[] = request_body httpURL.getBytes();
    的for(int i = 0; I< request_body.length;我++){
        _outStream.writeByte(request_body [I]);
    }
    DataInputStream以_inputStream =新DataInputStream所(httpConn.openInputStream());
    StringBuffer的_responseMessage =新的StringBuffer();
    INT CH;
    而((CH = _inputStream.read())!= - 1){
        _responseMessage.append((char)的CH);
    }
    字符串资源=(_responseMessage.toString());
    串响应= res.trim();
    的System.out.println(!!!!!!!!!!!!!!的回应是:+响应);
    httpConn.close();
}赶上(例外五){
    Dialog.alert(错误 - + e.toString());
}

在code工作的方式,我不完全理解。上述code的笔者建议为 httpURL 的服务器网址+我的JSON字符串使用。最终的结果是,我的服务器,而不是到达JSON字符串上,正在到达一个这样的字符串:

  HTTP://ip_of_my_server/phpServer/receiver2.php/ + jsonString

我不熟悉Java。我已经previously这样做的WP7和iOS,并在 httpUrl 我把我的服务器的URL,然后用一个命令我是的追加我的JSON字符串的http请求,一切工作正常。

如何追加以上的Htt prequest JSON字符串的,而不是让服务器到达JSON字符串而已?它添加到URL

编辑(提供已使用的code的其余部分)


  //用于指定连接类型(无线网络 - 科技3G  - 等)
公共静态字符串getConnectionString(){
    字符串的connectionString = NULL;
    //无线是preferred传输方法
    如果(WLANInfo.getWLANState()== WLANInfo.WLAN_STATE_CONNECTED){
        的connectionString =;接口=无线网络;
    }
    //是运营商网络连接的唯一途径?
    否则如果((CoverageInfo.getCoverageStatus()及CoverageInfo.COVERAGE_DIRECT)== CoverageInfo.COVERAGE_DIRECT){
        串carrierUid = getCarrierBIBSUid();
        如果(carrierUid == NULL){
            //有载体的覆盖面,但不青苗。因此,使用运营商的网络TCP
            的connectionString =; deviceside =真正的;
        }其他{
            //否则,使用UID来构造一个有效的载体青苗要求
            的connectionString =; deviceside = FALSE; connectionUID =+ carrierUid +; ConnectionType = MDS-公开;
        }
    }
    //检查的MDS连接,而不是(黑莓企业服务器)
    否则如果((CoverageInfo.getCoverageStatus()及CoverageInfo.COVERAGE_MDS)== CoverageInfo.COVERAGE_MDS){
        的connectionString =; deviceside =假;
    }
    //如果没有可用的连接中断,以避免不必要hassling用户
    否则如果(CoverageInfo.getCoverageStatus()== CoverageInfo.COVERAGE_NONE){
        的connectionString =无;
    }
    //从理论上讲,所有基地已涉及所以这不应该被reachable.But嘿嘿,以防万一......
    其他{
        的connectionString =; deviceside =真正的;
    }
    的System.out.println(!!!!!!!!!!!!!!连接类型是:+的connectionString);
    返回的connectionString;
    }/ **
 *通过手机的服务簿中查找的电信公司提供青苗
 *网络
 *
 返回:用于连接到该网络的UID。
 * /
私人同步静态字符串getCarrierBIBSUid(){
    ServiceRecord [] =记录ServiceBook.getSB()getRecords()。
    INT currentRecord;    为(currentRecord = 0; currentRecord&下; records.length; currentRecord ++){
        如果(记录[currentRecord] .getCid()。与toLowerCase()。等于(IPPP)){
            如果(记录[currentRecord] .getName()。与toLowerCase()
                    .indexOf(围兜)> = 0){
                返回记录[currentRecord] .getUid();
            }
        }
    }    返回null;
}


解决方案

的第一行应该只是您的网址

 字符串httpURL =HTTP://ip_of_my_server/phpServer/receiver2.php

你应该只发送JSON字符串到服务器的请求。

而不是字节[] = request_body httpURL.getBytes();

使用字节[] = request_body jsonString.getBytes();

下面是OS 5.0的方法和上面

 公共静态的HttpConnection getHttpConnection(字符串URL,字节[] POSTDATA){
    康涅狄格州的HttpConnection = NULL;
    出的OutputStream = NULL;
    尝试{
        康恩=(HttpConnection的)新的ConnectionFactory()的getConnection(URL).getConnection()。
        如果(参数conn!= NULL){
            如果(POSTDATA == NULL){
                conn.setRequestMethod(HttpConnection.GET);
                conn.setRequestProperty(用户代理,资料/ MIDP-2.0配置/ CLDC-1.0);
            }其他{
                conn.setRequestMethod(HttpConnection.POST);
                conn.setRequestProperty(内容长度,将String.valueOf(postData.length));
                conn.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
                conn.setRequestProperty(用户代理,资料/ MIDP-2.0配置/ CLDC-1.0);                OUT = conn.openOutputStream();
                out.write(POSTDATA);
                了out.flush();
            }
            如果(conn.getResponse code()!= 0){
                康涅狄格州返回;
            }
        }
    }赶上(例外五){
    } {最后
        尝试{
            out.close();
        }赶上(例外E2){
        }
    }    //只有当出现异常,我们关闭连接。
    //否则调用者应该关闭自己的连接。
    尝试{
        conn.close();
    }赶上(例外E1){
    }
    返回null;
}

下面是完整的类,如果你想让它与OS 4.2及以上工作。您可能需要通过其值1来代替恒定COVERAGE_DIRECT,如果你想以&lt编译它; 4.5。

 公共类ConnectionHelper {
    / **
     *返回工作连接类型。连接类型可以是BIS,BES,TCP,WAP2,TCPIP
     * /
    公共静态的HttpConnection getHttpConnection(字符串URL,字节[] POSTDATA){
        INT [] preferredOrder = INT新[] {CONNECTION_WIFI,CONNECTION_BIS,CONNECTION_BES,CONNECTION_UNITE,CONNECTION_WAP2,CONNECTION_TCPIP,};        的for(int i = 0; I< preferredOrder.length;我++){
            整型= preferredOrder [I]
            如果(是present(类型)){
                康涅狄格州的HttpConnection = NULL;
                出的OutputStream = NULL;
                尝试{
                    康恩=(HttpConnection的)Connector.open(convertURL(类型,URL));
                    如果(参数conn!= NULL){
                        如果(POSTDATA == NULL){
                            conn.setRequestMethod(HttpConnection.GET);
                            conn.setRequestProperty(用户代理,资料/ MIDP-2.0配置/ CLDC-1.0);
                        }其他{
                            conn.setRequestMethod(HttpConnection.POST);
                            conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,将String.valueOf(postData.length));
                            conn.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
                            conn.setRequestProperty(用户代理,资料/ MIDP-2.0配置/ CLDC-1.0);                            OUT = conn.openOutputStream();
                            out.write(POSTDATA);
                            了out.flush();
                        }
                        如果(conn.getResponse code()!= 0){
                            康涅狄格州返回;
                        }
                    }
                }赶上(例外五){
                } {最后
                    尝试{
                        out.close();
                    }赶上(例外E2){
                    }
                }
            }
        }
        //只有当出现异常,我们关闭连接。
        //否则调用者应该关闭自己的连接。
        尝试{
            conn.close();
        }赶上(例外E1){
        }        返回null;
    }    如果发现/ **存储运输ServiceBooks。否则,空* /
    私有静态ServiceRecord srMDS,srWiFi,srBIS,srWAP2,srUnite;    私有静态最终诠释CONNECTION_DEFAULT = 0;
    私有静态最终诠释CONNECTION_BIS = 1;
    私有静态最终诠释CONNECTION_BES = 2;
    私有静态最终诠释CONNECTION_TCPIP = 3;
    私有静态最终诠释CONNECTION_WIFI = 4;
    私有静态最终诠释CONNECTION_WAP2 = 5;
    私有静态最终诠释CONNECTION_UNITE = 6;    私有静态最终诠释CONFIG_TYPE_BES = 1;    私有静态最后弦乐UNITE_NAME =团结;    私有静态无效checkTransportAvailability(){
        initializeTransportAvailability();
    }    / **
     *初始化ServiceRecord实例,每个传输(如果可用)。否则,离开它空。还确定是否有足够的覆盖范围内时针对每个传输
     *和覆盖套*标志。
     * /
    私有静态无效initializeTransportAvailability(){
        ServiceBook SB = ServiceBook.getSB();
        ServiceRecord [] =记录sb.getRecords();        的for(int i = 0; I< records.length;我++){
            ServiceRecord myRecord =记录[I]
            串CID,UID;            如果(myRecord.isValid()及&放大器;!myRecord.isDisabled()){
                CID = myRecord.getCid()与toLowerCase()。
                UID = myRecord.getUid()与toLowerCase()。                // BIS
                如果(cid.indexOf(IPPP)= -1&放大器;!&放大器;!uid.indexOf(gpmds)= -1){
                    srBIS = myRecord;
                }                // BES
                如果(cid.indexOf(IPPP)= -1&安培;!&安培; uid.indexOf(gpmds)== -1){
                    srMDS = myRecord;
                }
                // 无线上网
                如果(cid.indexOf(wptcp)= -1&放大器;!&放大器;!uid.indexOf(无线)= -1){
                    srWiFi = myRecord;
                }                // WAP2.0
                如果(cid.indexOf(wptcp)= -1&安培;!&安培; uid.indexOf(无线)== -1放大器;&安培; uid.indexOf(MMS)== -1){
                    srWAP2 = myRecord;
                }                //联合
                如果(getConfigType(myRecord)== CONFIG_TYPE_BES和放大器;&安培; myRecord.getName()等于(UNITE_NAME)){
                    srUnite = myRecord;
                }
            }
        }
    }    / **
     *获取使用getDataInt低于ServiceRecord的配置类型
     *
     * @参数记录
     *一个ServiceRecord
     * @返回ServiceRecord的configType
     * /
    私有静态诠释getConfigType(ServiceRecord记录){
        返回getDataInt(纪录,12);
    }    / **
     *获取ServiceRecord的配置类型。传递12类型返回configType。
     *
     * @参数记录
     *一个ServiceRecord
     * @参数类型
     * 数据类型
     * @返回configType
     * /
    私有静态诠释getDataInt(ServiceRecord记录,整型){
        DataBuffer中缓冲= NULL;
        缓冲= getDataBuffer(记录型);        如果(缓冲!= NULL){
            尝试{
                返回ConverterUtilities.readInt(缓冲液);
            }赶上(抛出:EOFException E){
                返回-1;
            }
        }
        返回-1;
    }    / **
     *为getDataInt实用方法()
     * /
    私有静态的DataBuffer getDataBuffer(ServiceRecord记录,整型){
        字节[]数据= record.getApplicationData();
        如果(数据!= NULL){
            DataBuffer中的缓冲区=新的DataBuffer(数据,0,data.length,真正的);
            尝试{
                buffer.readByte();
            }赶上(抛出:EOFException E1){
                返回null;
            }
            如果(ConverterUtilities.findType(缓冲,类型)){
                返回缓冲区;
            }
        }
        返回null;
    }    私有静态字符串convertURL(INT connectionType,字符串URL){
        开关(connectionType){
        案例CONNECTION_BES:
            网址+ =; deviceside =假;
            打破;
        案例CONNECTION_BIS:
            网址+ =; deviceside =假+; ConnectionType = MDS-公开;
            打破;
        案例CONNECTION_TCPIP:
            网址+ =; deviceside =真正的;
            打破;
        案例CONNECTION_WIFI:
            网址+ =;接口=无线网络;
            打破;
        案例CONNECTION_WAP2:
            网址+ =; deviceside = TRUE; ConnectionUID =+ srWAP2.getUid();
            打破;
        案例CONNECTION_UNITE:
            网址+ =; deviceside = FALSE; ConnectionUID =+ srUnite.getUid();
            打破;
        }        返回URL;
    }    私有静态布尔是present(INT connectionType){
        checkTransportAvailability();        开关(connectionType){
        案例CONNECTION_BIS:
            返回(srBIS = NULL&放大器;!&安培; CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B));        案例CONNECTION_BES:
            回报(srMDS = NULL&放大器;!&安培; CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS));        案例CONNECTION_WIFI:
            回报(srWiFi = NULL&放大器;!&安培; CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT,RadioInfo.WAF_WLAN,FALSE));        案例CONNECTION_TCPIP:
            回报(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT));        案例CONNECTION_WAP2:
            回报(srWAP2 = NULL&放大器;!&安培; CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT));        案例CONNECTION_UNITE:
            回报(srUnite = NULL&放大器;!&安培; CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS));        案例CONNECTION_DEFAULT:
            返回true;
        }        返回false;
    }
}

和最终发布的数据。

 公共无效sendJson(字符串jsonString){
    字符串httpURL =HTTP://ip_of_my_server/phpServer/receiver2.php
    的HttpConnection httpConn = NULL;    尝试{
        httpConn = getHttpConnection(httpURL,jsonString.getBytes());        如果(httpConn.getResponse code()== 200){
            //如果需要输出,然后读取它。否则注释掉它。
            字节[]数据= IOUtilities.streamToBytes(httpConn.openInputStream());
            字符串的响应=新的String(数据);
            的System.out.println(!!!!!!!!!!!!!!的回应是:+响应);
        }
    }赶上(例外五){
    }
    最后{
        尝试{
            httpConn.close();
        }赶上(例外E2){
        }
    }
}

I am trying to send a json string , from my BlackBerry OS < 7.X application to my Server. I am trying to use an HTTP Post request. What i have done so far is :

String httpURL = "http://ip_of_my_server/phpServer/receiver2.php/" + jsonString;

try {
    HttpConnection httpConn;
    httpConn = (HttpConnection) Connector.open(httpURL + getConnectionString());
    httpConn.setRequestMethod(HttpConnection.POST);
    httpConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
    byte[] request_body = httpURL.getBytes();
    for (int i = 0; i < request_body.length; i++) {
        _outStream.writeByte(request_body[i]);
    }
    DataInputStream _inputStream = new DataInputStream(httpConn.openInputStream());
    StringBuffer _responseMessage = new StringBuffer();
    int ch;
    while ((ch = _inputStream.read()) != -1) {
        _responseMessage.append((char) ch);
    }
    String res = (_responseMessage.toString());
    String response = res.trim();
    System.out.println("!!!!!!!!!!!!!! Response is: " + response);
    httpConn.close();
} catch (Exception e) {
    Dialog.alert("Error - " + e.toString());
}

The code works in a way that i dont fully understand. The author of the above code suggested to use as an httpURL the URL of the server + my json string. The final result is that on my server instead of arriving the json string , is arriving a string like that :

http://ip_of_my_server/phpServer/receiver2.php/ + jsonString

I am not familiar with java. I have previously done this for WP7 and iOS and in the httpUrl i put my servers URL and then with a command i was "appending" my json string to the http request and everything worked as expected.

How can i append the json string to the above HttpRequest , instead of adding it to the URL so that in the server arrives the JSON String only?

EDIT (providing the rest of the code that was used)


//used to specify connection type ( wifi - 3g - etc )
public static String getConnectionString() {
    String connectionString = null;
    // Wifi is the preferred transmission method
    if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
        connectionString = ";interface=wifi";
    }
    // Is the carrier network the only way to connect?
    else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
        String carrierUid = getCarrierBIBSUid();
        if (carrierUid == null) {
            // Has carrier coverage, but not BIBS. So use the carrier's TCP network
            connectionString = ";deviceside=true";
        } else {
            // otherwise, use the Uid to construct a valid carrier BIBS request
            connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
        }
    }
    // Check for an MDS connection instead (BlackBerry Enterprise Server)
    else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
        connectionString = ";deviceside=false";
    }
    // If there is no connection available abort to avoid hassling the user unnecessarily
    else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
        connectionString = "none";
    }
    // In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
    else {
        connectionString = ";deviceside=true";
    }
    System.out.println("!!!!!!!!!!!!!! Connection type is: " + connectionString);
    return connectionString;
    }

/**
 * Looks through the phone's service book for a carrier provided BIBS
 * network
 * 
 * @return The uid used to connect to that network.
 */
private synchronized static String getCarrierBIBSUid() {
    ServiceRecord[] records = ServiceBook.getSB().getRecords();
    int currentRecord;

    for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
        if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
            if (records[currentRecord].getName().toLowerCase()
                    .indexOf("bibs") >= 0) {
                return records[currentRecord].getUid();
            }
        }
    }

    return null;
}

解决方案

The the first line should be simply your URL

String httpURL = "http://ip_of_my_server/phpServer/receiver2.php";

And you should only send the json string to the server as request.

instead of byte[] request_body = httpURL.getBytes();

use byte[] request_body = jsonString.getBytes();

Here is the method for OS 5.0 and above

public static HttpConnection getHttpConnection(String url, byte[] postData) {
    HttpConnection conn = null;
    OutputStream out = null;
    try {
        conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
        if (conn != null) {
            if (postData == null) {
                conn.setRequestMethod(HttpConnection.GET);
                conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            } else {
                conn.setRequestMethod(HttpConnection.POST);
                conn.setRequestProperty("Content-Length", String.valueOf(postData.length));
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");

                out = conn.openOutputStream();
                out.write(postData);
                out.flush();
            }
            if (conn.getResponseCode() != 0) {
                return conn;
            }
        }
    } catch (Exception e) {
    } finally {
        try {
            out.close();
        } catch (Exception e2) {
        }
    }

    //Only if exception occurs, we close the connection.
    //Otherwise the caller should close the connection himself.
    try {
        conn.close();
    } catch (Exception e1) {
    }
    return null;
}

Here is the complete class if you want it to work with OS 4.2 and above. You may need to replace the constant COVERAGE_DIRECT by its value 1, if you want to compile it with < 4.5.

public class ConnectionHelper {
    /**
     * Returns the working connection type. The connection types can be BIS, BES, TCP, WAP2, TCPIP
     */
    public static HttpConnection getHttpConnection(String url, byte[] postData) {
        int[] preferredOrder = new int[] { CONNECTION_WIFI, CONNECTION_BIS, CONNECTION_BES, CONNECTION_UNITE, CONNECTION_WAP2, CONNECTION_TCPIP, };

        for (int i = 0; i < preferredOrder.length; i++) {
            int type = preferredOrder[i];
            if (isPresent(type)) {
                HttpConnection conn = null;
                OutputStream out = null;
                try {
                    conn = (HttpConnection) Connector.open(convertURL(type, url));
                    if (conn != null) {
                        if (postData == null) {
                            conn.setRequestMethod(HttpConnection.GET);
                            conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
                        } else {
                            conn.setRequestMethod(HttpConnection.POST);
                            conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postData.length));
                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");

                            out = conn.openOutputStream();
                            out.write(postData);
                            out.flush();
                        }
                        if (conn.getResponseCode() != 0) {
                            return conn;
                        }
                    }
                } catch (Exception e) {
                } finally {
                    try {
                        out.close();
                    } catch (Exception e2) {
                    }
                }
            }
        }
        // Only if exception occurs, we close the connection.
        // Otherwise the caller should close the connection himself.
        try {
            conn.close();
        } catch (Exception e1) {
        }

        return null;
    }

    /** Stores transport ServiceBooks if found. Otherwise, null */
    private static ServiceRecord srMDS, srWiFi, srBIS, srWAP2, srUnite;

    private static final int CONNECTION_DEFAULT = 0;
    private static final int CONNECTION_BIS = 1;
    private static final int CONNECTION_BES = 2;
    private static final int CONNECTION_TCPIP = 3;
    private static final int CONNECTION_WIFI = 4;
    private static final int CONNECTION_WAP2 = 5;
    private static final int CONNECTION_UNITE = 6;

    private static final int CONFIG_TYPE_BES = 1;

    private static final String UNITE_NAME = "Unite";

    private static void checkTransportAvailability() {
        initializeTransportAvailability();
    }

    /**
     * Initializes the ServiceRecord instances for each transport (if available). Otherwise leaves it null. Also determines if sufficient coverage is available for each transport
     * and sets coverage* flags.
     */
    private static void initializeTransportAvailability() {
        ServiceBook sb = ServiceBook.getSB();
        ServiceRecord[] records = sb.getRecords();

        for (int i = 0; i < records.length; i++) {
            ServiceRecord myRecord = records[i];
            String cid, uid;

            if (myRecord.isValid() && !myRecord.isDisabled()) {
                cid = myRecord.getCid().toLowerCase();
                uid = myRecord.getUid().toLowerCase();

                // BIS
                if (cid.indexOf("ippp") != -1 && uid.indexOf("gpmds") != -1) {
                    srBIS = myRecord;
                }

                // BES
                if (cid.indexOf("ippp") != -1 && uid.indexOf("gpmds") == -1) {
                    srMDS = myRecord;
                }
                // WiFi
                if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") != -1) {
                    srWiFi = myRecord;
                }

                // Wap2.0
                if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1 && uid.indexOf("mms") == -1) {
                    srWAP2 = myRecord;
                }

                // Unite
                if (getConfigType(myRecord) == CONFIG_TYPE_BES && myRecord.getName().equals(UNITE_NAME)) {
                    srUnite = myRecord;
                }
            }
        }
    }

    /**
     * Gets the config type of a ServiceRecord using getDataInt below
     * 
     * @param record
     *            A ServiceRecord
     * @return configType of the ServiceRecord
     */
    private static int getConfigType(ServiceRecord record) {
        return getDataInt(record, 12);
    }

    /**
     * Gets the config type of a ServiceRecord. Passing 12 as type returns the configType.
     * 
     * @param record
     *            A ServiceRecord
     * @param type
     *            dataType
     * @return configType
     */
    private static int getDataInt(ServiceRecord record, int type) {
        DataBuffer buffer = null;
        buffer = getDataBuffer(record, type);

        if (buffer != null) {
            try {
                return ConverterUtilities.readInt(buffer);
            } catch (EOFException e) {
                return -1;
            }
        }
        return -1;
    }

    /**
     * Utility Method for getDataInt()
     */
    private static DataBuffer getDataBuffer(ServiceRecord record, int type) {
        byte[] data = record.getApplicationData();
        if (data != null) {
            DataBuffer buffer = new DataBuffer(data, 0, data.length, true);
            try {
                buffer.readByte();
            } catch (EOFException e1) {
                return null;
            }
            if (ConverterUtilities.findType(buffer, type)) {
                return buffer;
            }
        }
        return null;
    }

    private static String convertURL(int connectionType, String url) {
        switch (connectionType) {
        case CONNECTION_BES:
            url += ";deviceside=false";
            break;
        case CONNECTION_BIS:
            url += ";deviceside=false" + ";ConnectionType=mds-public";
            break;
        case CONNECTION_TCPIP:
            url += ";deviceside=true";
            break;
        case CONNECTION_WIFI:
            url += ";interface=wifi";
            break;
        case CONNECTION_WAP2:
            url += ";deviceside=true;ConnectionUID=" + srWAP2.getUid();
            break;
        case CONNECTION_UNITE:
            url += ";deviceside=false;ConnectionUID=" + srUnite.getUid();
            break;
        }

        return url;
    }

    private static boolean isPresent(int connectionType) {
        checkTransportAvailability();

        switch (connectionType) {
        case CONNECTION_BIS:
            return (srBIS != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B));

        case CONNECTION_BES:
            return (srMDS != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS));

        case CONNECTION_WIFI:
            return (srWiFi != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT, RadioInfo.WAF_WLAN, false));

        case CONNECTION_TCPIP:
            return (CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT));

        case CONNECTION_WAP2:
            return (srWAP2 != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT));

        case CONNECTION_UNITE:
            return (srUnite != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS));

        case CONNECTION_DEFAULT:
            return true;
        }

        return false;
    }
}

And finally post your data.

public void sendJson(String jsonString) {
    String httpURL = "http://ip_of_my_server/phpServer/receiver2.php";
    HttpConnection httpConn = null;

    try {
        httpConn = getHttpConnection(httpURL, jsonString.getBytes());

        if(httpConn.getResponseCode() == 200) {
            //If you need the output, then read it. Otherwise comment it.
            byte[] data = IOUtilities.streamToBytes(httpConn.openInputStream());
            String response = new String(data);
            System.out.println("!!!!!!!!!!!!!! Response is: " + response);
        }
    } catch (Exception e) {
    }
    finally {
        try {
            httpConn.close();
        } catch (Exception e2) {
        }
    }
}

这篇关于黑莓HTTP POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆